//
//  UcfgroupXMPPManger.m
//  WXIM
//
//  Created by fusuwei on 14-6-12.
//  Copyright (c) 2014年 fusuwei. All rights reserved.
//

#import "UcfgroupXMPPManger.h"
#import "GCDAsyncSocket.h"
#import "XMPP.h"
#import "XMPPStream.h"
#import "XMPPReconnect.h"
#import "XMPPMessage.h"
#import "TURNSocket.h"

#import "PublicMacros.h"
#import "EPublicMacros.h"

#import "ChatContact.h"
#import "ChatContactMgr.h"
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "YY_FMDatabase.h"
#import "ChatMessageMgr.h"
#import "EWxChatMgrContactDelegate.h"

#import "ChatLoginUserMgr.h"
#import "ucfCallmgr.h"

#import "IWxChatMgrGroup.h"

#import "ChatTextMessage.h"
#import "ChatAudioMessage.h"
#import "ChatCustomMessage.h"
#import "ChatPhotoMessage.h"
#import "ChatVideoMessage.h"
#import "ChatFileMessage.h"

#import "HttpURLConnection.h"
#import "Utility.h"
#import "NSString+Time.h"
#import "IWxChatMgrLogin.h"
#import "NSString+Path.h"


EWxLoginRegState loginOrRegState = connectserver_Error;


@interface UcfgroupXMPPManger() <NSURLConnectionDataDelegate,XMPPReconnectDelegate,UIAlertViewDelegate>
{
    NSTimer *reConnectTimer;
    BOOL isReConnecting;
}

@property (nonatomic,strong)NSMutableData *uploadData;
@end

@implementation UcfgroupXMPPManger
{
	XMPPReconnect *xmppReconnect;
    XMPPRoster *xmppRoster;
 //   XMPPRosterCoreDataStorage *xmppRosterStorage;
    
    // 创建支持vCard
//    XMPPvCardCoreDataStorage *xmppvCardStorage;
 //   XMPPvCardTempModule *xmppvCardTempModule;
//    XMPPvCardAvatarModule *xmppvCardAvatarModule;
    
 //   XMPPCapabilitiesCoreDataStorage *xmppCapabilitiesStorage;
 //   XMPPCapabilities *xmppCapabilities;

    XMPPAutoPing *_xmppAutoPing;
    
   	NSString *password;
	
	BOOL allowSelfSignedCertificates;
	BOOL allowSSLHostNameMismatch;
	
	BOOL isXmppConnected; //是否是连接成功状态
    
    BOOL isLoginSuccess; //是否已经登录成功
    
}



@synthesize xmppStream;
@synthesize xmppAutoPing;

@synthesize xmppContactDelegate; //联系人模块
@synthesize xmppLogRegDelegate; //登录、注册代理
@synthesize xmppGroupDelegate; //群组代理


@synthesize logRegWxUserObject; //当前注册或登录的用户


static UcfgroupXMPPManger *sharedManager;

+(UcfgroupXMPPManger*)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager=[[UcfgroupXMPPManger alloc] init];
        [sharedManager setupStream];
    });
    return sharedManager;
}


- (void)dealloc
{
	[self teardownStream];
    
    //Vincefu
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - 发送文件之前的操作－－图片、语音、视频
- (void)sendFileForSize:(long)size
               fileName:(NSString *)imageName
               fileDate:(NSData *)imageData
             andDelegate:(id)delegate
{
    
    [self.xmppUpload requestSlotForFilename:imageName size:size contentType:@"image/jpeg/mp3/mov"];
    [self.xmppUpload addDelegate:delegate delegateQueue:dispatch_get_main_queue()];
}





//recive message to send ACK
- (void)sendReciveMsgAckfromJid:(NSString *)fromJid to:(NSString *)toJid msgId:(NSString *)msgid isGroup:(BOOL)isGroup
{
    WXLog(@"sendReciveMsgAckfromJid: msgid= %@",msgid);
    if (isGroup) {
        if (![toJid hasSuffix:kXMPPMyBareDomain]) {
            toJid = [NSString stringWithFormat:@"%@@%@",toJid,kXMPPGroupDomain];
        }
    }else{
        if (![toJid hasSuffix:kXMPPMyBareDomain]) {
            toJid = [NSString stringWithFormat:@"%@@%@",toJid,kXMPPMyBareDomain];
        }
    }
    
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"from" stringValue:fromJid];
    [message addAttributeWithName:@"to" stringValue:toJid];
    
    NSString *messageID = [NSString stringWithFormat:@"%@%@",@"sendReciveMsgAck",[NSString stringWithFormat:@"%d",[self getRandomNumber:1000000 to:9000000]]];
    [message addAttributeWithName:@"id" stringValue:messageID];
    
    NSXMLElement *received = [NSXMLElement elementWithName:@"received" xmlns:@"urn:xmpp:receipts"];
    [received addAttributeWithName:@"id" stringValue:msgid];
    [message addChild:received];
    [xmppStream sendElement:message];
}

#pragma mark --------配置XML流---------
- (void)setupStream
{
	NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
	
    self.isReg = NO;
    self.logRegWxUserObject = [[ChatLoginUser alloc] init];
    
    //reqTimer和reqId和reqDone数组
    self.timerIdList = [[NSMutableArray alloc] initWithCapacity:10];
    
    
	xmppStream = [[XMPPStream alloc] init];
    xmppStream.isRegister = self.isReg;
    xmppStream.requestedpassword = self.logRegWxUserObject.UserPassword;
    
    self.xmppUpload = [[XMPPHTTPFileUpload alloc] initWithServiceName:kXmppUploadFileDomain];
    [self.xmppUpload activate:xmppStream];

#if !TARGET_IPHONE_SIMULATOR
	{
        // 设置后台也进行连接
        xmppStream.enableBackgroundingOnSocket = YES;
	}
#endif
	
    // 创建XMPPStream重联
	xmppReconnect = [[XMPPReconnect alloc] init];
    xmppReconnect.autoReconnect = YES;
	
    // 创建XMPP花名册 XMPPRosterCoreDataStorage 为xmppRoster的代理，里面实现了coreData的保存。
//    xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
    
	
//	xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
	
	xmppRoster.autoFetchRoster = NO;  //自动获取
	xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = NO;
    
    
//    // 创建支持vCard
//    xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
//    xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];
//    
//    xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];
    
    // Setup capabilities
//    xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
//    xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];
    
//    xmppCapabilities.autoFetchHashedCapabilities = YES;
//    xmppCapabilities.autoFetchNonHashedCapabilities = NO;
    
    
    // Activate xmpp modules
    
    [xmppReconnect         activate:xmppStream];
    [xmppRoster            activate:xmppStream];
//    
//    [xmppvCardTempModule   activate:xmppStream];
//    [xmppvCardAvatarModule activate:xmppStream];
 //   [xmppCapabilities      activate:xmppStream];
    
    // Add ourself as a delegate to anything we may be interested in
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];

//	
//	[xmppStream setHostName:kXMPPmyHostAddr];
//	[xmppStream setHostPort:kXMPPmyHostPort];
	
    
	// 可能需要改变这些设置根据你连接到服务器
	allowSelfSignedCertificates = NO;
	allowSSLHostNameMismatch = NO;
    
#if 0 //fusuwei
    if (![self connect]) {
        [[[UIAlertView alloc]initWithTitle:@"服务器连接失败" message:@"连接服务器失败！" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil]show];
    };
#endif
}

- (void)teardownStream
{
    WXLog(@"teardownStream ");
    
    [xmppStream removeDelegate:self];
    [xmppRoster removeDelegate:self];
    
    [self.xmppUpload deactivate];
    
    [xmppReconnect         deactivate];
    [xmppRoster            deactivate];
    
//    [xmppvCardTempModule   deactivate];
//    [xmppvCardAvatarModule deactivate];
//    [xmppCapabilities      deactivate];
    
    [xmppStream disconnect];
    
    xmppStream = nil;
    xmppReconnect = nil;
    
    xmppRoster = nil;
    self.xmppUpload = nil;
//    xmppRosterStorage = nil;
//    xmppvCardStorage = nil;
//    xmppvCardTempModule = nil;
//    xmppvCardAvatarModule = nil;
//    xmppCapabilities = nil;
//    xmppCapabilitiesStorage = nil;
    
    [self deactivateXmppAutoPing];
}

#pragma mark ------ XMPPReconnectDelegate -------
- (void)xmppReconnect:(XMPPReconnect *)sender didDetectAccidentalDisconnect:(SCNetworkReachabilityFlags)connectionFlags
{
    WXLog(@"didDetectAccidentalDisconnect-- %d",connectionFlags);
//    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"Title" message:@"didDetectAccidentalDisconnect" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    [alter show];
    
    [self becomeActive:nil];
}

- (BOOL)xmppReconnect:(XMPPReconnect *)sender shouldAttemptAutoReconnect:(SCNetworkReachabilityFlags)reachabilityFlags
{
    WXLog(@"shouldAttemptAutoReconnect-- %d",reachabilityFlags);
//    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"Title" message:@"shouldAttemptAutoReconnect" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    [alter show];
    
    [self becomeActive:nil];
    
    return YES;
}

// 向服务器发送上线操作.
- (void)ucfgroupGoOnline
{
    WXLog(@"ucfgroupGoOnline-- %@",logRegWxUserObject.UserId);
    
    NSString *self_id = [NSString stringWithFormat:@"ucfgroupGoOnline_%@",logRegWxUserObject.UserId];
	XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit // type默认为available
    [presence addAttributeWithName:@"id" objectValue:self_id];
	
	[xmppStream sendElement:presence];
}

// 向服务器发送下线操作
- (void)goOffline
{
	XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
	
	[xmppStream sendElement:presence];
}

#pragma mark - connect ---
// 连接服务器
- (BOOL)connect
{
    loginOrRegState = connectserver_Error;
    
    xmppStream.isRegister = self.isReg;
    xmppStream.requestedpassword = self.logRegWxUserObject.UserPassword;

    
    if (![xmppStream isDisconnected]) {
		return YES; // 如果已经连接
	}
    if (!self.isReg) {
        //Vincefu
// wjy 修改，后台切前台的时候，未放置自动重连 耗费时间较多，导致，重连服务的过程中，发消息失败。顾切到前台的时候，立即重连服务器。
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(becomeActive:)
                                                     name:UIApplicationDidBecomeActiveNotification object:nil];
#if 0
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(resignActive:)
                                                     name:UIApplicationWillResignActiveNotification object:nil];
#endif
        //fuweivince
        if (reConnectTimer == nil) {
            reConnectTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        }
    }
    
//	NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
//	NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
    
    //读取个人登陆账号和密码----fusuwei
    NSString *myJID = logRegWxUserObject.UserId;
    NSString *myPassword = logRegWxUserObject.UserPassword;
    
    {
        [[NSUserDefaults standardUserDefaults] setObject:myJID forKey:kXMPPmyJID];
        [[NSUserDefaults standardUserDefaults] setObject:myPassword forKey:kXMPPmyPassword];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

	// If you don't want to use the Settings view to set the JID,
	// uncomment the section below to hard code a JID and password.
	//
	// myJID = @"user@gmail.com/xmppframework";
	// myPassword = @"";
    // 设置服务器域名,如果不设置默认为账号后面的域名//
	
	if (myJID == nil || myPassword == nil) {
		return NO;
	}
    
	// ===这句注释掉 改成下面这句   [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
    //[xmppStream setMyJID:[XMPPJID jidWithUser:myJID domain:@"hcios.com" resource:@"ios"]];

    
    //设置用户
	[xmppStream setMyJID:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@/%@",myJID,[self generateXMPPresource]]]];
    //[xmppStream setMyJID:[XMPPJID jidWithUser:myJID domain:kXMPPmyDomain resource:[self generateXMPPresource]]];
    
    //密码
	password = myPassword;
    
    //设置服务器
    [xmppStream setHostName:kXMPPmyHostAddr];
    [xmppStream setHostPort:kXMPPmyHostPort];

    
    WXLog(@"正在登陆连接........");
    //连接服务器
    NSError *error = nil;
	if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
	{
        // 如果连接出了问题（这里一般是404错误，要么是无网络，要么是不能访问）
		WXLog(@"Error connecting: %@", error);
        
        isLoginSuccess = NO;
        
        if (self.isReg)
        {
            //注册失败--联网失败
            if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
            {
                [xmppLogRegDelegate registerNewAccountRspState:connectserver_Error username:[Utility getBareContactId:logRegWxUserObject.UserId] password:logRegWxUserObject.UserPassword];
            }
        }
        else
        {
            NSString *errordescribe = [NSString stringWithFormat:@"error:%ld",(long)[error code]];
            NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [Utility getBareContactId:logRegWxUserObject.UserId], @"userid", logRegWxUserObject.UserPassword, @"password",
                                       @"联网失败", @"describe",
                                       errordescribe,@"errorCode",nil];
            if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
            {
                [xmppLogRegDelegate loginWithUserIdRspState:login_Fail loginInfo:loginInfo];
            }
            
            if (self.completion) {
                self.completion(loginInfo, connectserver_Error);
            }
        }
        
		return NO;
	}
    
	return YES;
}

// 取消连接
- (void)disconnect
{
	[self goOffline];
	[xmppStream disconnect];
    
    isLoginSuccess = NO;
}

- (void)disconnectAfterSending
{
    [xmppStream disconnectAfterSending];
}

- (NSManagedObjectContext *)managedObjectContext_roster
{
    return nil;
 //   return [xmppRosterStorage mainThreadManagedObjectContext];
}

#pragma mark ------ XMPPStream Delegate -------

//成功连接服务器
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
	WXLog(@"socketDidConnect 成功连接服务器");
}

- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
	WXLog(@"willSecureWithSettings");;
	
	if (allowSelfSignedCertificates)
	{
	//	[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
	}
	
	if (allowSSLHostNameMismatch)
	{
		[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
	}
	else
	{
		// Google does things incorrectly (does not conform to RFC).
		// Because so many people ask questions about this (assume xmpp framework is broken),
		// I've explicitly added code that shows how other xmpp clients "do the right thing"
		// when connecting to a google server (gmail, or google apps for domains).
		
		NSString *expectedCertName = nil;
		
		NSString *serverDomain = xmppStream.hostName;
		NSString *virtualDomain = [xmppStream.myJID domain];
		
		if ([serverDomain isEqualToString:@"talk.google.com"])
		{
			if ([virtualDomain isEqualToString:@"gmail.com"])
			{
				expectedCertName = virtualDomain;
			}
			else
			{
				expectedCertName = serverDomain;
			}
		}
		else if (serverDomain == nil)
		{
			expectedCertName = virtualDomain;
		}
		else
		{
			expectedCertName = serverDomain;
		}
		
		if (expectedCertName)
		{
			[settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
		}
	}
}

- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
	WXLog(@"xmppStreamDidSecure: %@", sender);
}

#pragma mark - xmppStreamDidConnect
// 连接成功 我们在这个函数里再对其做用户名和密码验证
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
	WXLog(@"xmppStreamDidConnect: 连接成功");
	
	isXmppConnected = YES;
    
    xmppStream.isRegister = self.isReg;
    xmppStream.requestedpassword = self.logRegWxUserObject.UserPassword;

	
	NSError *error = nil;
    if (self.isReg)
    {
        if (![xmppStream registerWithPassword:password error:&error])
        {
            
        }
    }
    else
    {
//fusuwei modify it @2014-09-10
        if (![xmppStream authenticateWithPassword:password error:&error])
        {
            //WXLog(@"Error authenticating: %@", error);
        }
        return;
    }
}

#pragma mark - xmppStreamDidRegister
// 用户通过验证
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
	WXLog(@"xmppStreamDidAuthenticate: 用户通过验证");
    
    isLoginSuccess = YES;
    
    //用户登录响应
    if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
    {
        [self deleteXmppRecordReqId:@"loginWithUserId"];
        NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [Utility getBareContactId:logRegWxUserObject.UserId], @"userid", logRegWxUserObject.UserPassword, @"password",
                                   @"用户通过验证", @"describe",nil];
        [xmppLogRegDelegate loginWithUserIdRspState:login_OK loginInfo:loginInfo];
    }
    
    //保存个人登陆账号和密码----fusuwei
    [ChatLoginUserMgr saveChatLoginUser:logRegWxUserObject];
    
    
    [self ucfgroupGoOnline]; //发送上线通知---Vince
}

// 用户验证失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
	WXLog(@"didNotAuthenticate: 用户验证失败");

    //用户登录失败
    if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
    {
        [self deleteXmppRecordReqId:@"loginWithUserId"];
        NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [Utility getBareContactId:logRegWxUserObject.UserId], @"userid", logRegWxUserObject.UserPassword, @"password",
                                   @"用户验证失败", @"describe",nil];
        [xmppLogRegDelegate loginWithUserIdRspState:login_Fail loginInfo:loginInfo];
    }
    
    [self disconnect];
}

#pragma mark -  --------------*********didReceiveIQ**********--------------------
//收到  好友列表，在 XMPP 中被称为 roster，花名册
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    WXLog(@"didReceiveIQ: 收到iq ＝ %@ id：%@\n\r",iq,[iq elementID]);
    
 //   NSLog(@"收到iq:%@\n\r",iq);
    [self deleteXmppRecordReqId:[iq elementID]];
    
    //拨打电话控制流程 判断iq.type串中是否包含ucfCallMgr_这个串，
    if ([iq.elementID hasPrefix:@"ucfCallMgr_"] == 1)
    {
        [[ucfCallMgr sharedInstance] xmppStream:sender didReceiveIQ:iq];
        return YES;
    }
    
    //NSString *from = [[iq from] bare]; //iq.fromStr;
    //NSString *to = [[iq to] bare]; //iq.toStr;
    
#pragma mark---------iq返回error-----------
    if ([@"error" isEqualToString:iq.type])
    {
        //删除联系人返回error  ----目前服务器没有error回应
        if ([iq.elementID hasPrefix:@"ucfgroup_removeBuddy"])
        {
            NSString *nameJid = [iq.elementID pathExtension];
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(removeContactRsp:contactId:errorState:)])
            {
                [xmppContactDelegate removeContactRsp:Contact_Failure contactId:nameJid errorState:Contact_Sever_Error];
            }
            return YES;
        }
        //修改备注---昵称 返回error  ----目前服务器没有error回应
        else if ([iq.elementID hasPrefix:@"ucfgroup_setNickname"])
        {
            NSString *nameJid = [iq.elementID pathExtension];
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(remarkContactRsp:contactId:errorState:)])
            {
                [xmppContactDelegate remarkContactRsp:Contact_Failure contactId:nameJid errorState:Contact_Sever_Error];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"ucfgroup_CreateGroupName"]){
            //收到 创建 ucfgroup_CreateGroupName 返回error
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *create = [group elementForName:@"create"];
            NSString *group_id = [create attributeStringValueForName:@"group_id"];
            
            NSString *pre_group_id = iq.elementID; //预保存的群Id
            
            [ChatGroupMgr deleteGroupListByGroupId:pre_group_id];
            
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(creatGroupNameRspState:groupId:withMsg:)])
            {
                [xmppGroupDelegate creatGroupNameRspState:Group_Failure groupId:group_id withMsg:errorCode];
            }
            return YES;
        }else if ([iq.elementID isEqualToString:@"initAllContactGroups"]){
            //初始化群组并获取所有群列表和群成员列表error
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(creatGroupNameRspState:groupId:withMsg:)])
            {
                [xmppGroupDelegate creatGroupNameRspState:Group_Failure groupId:nil withMsg:errorCode];
            }
            
            if (self.contactGroupCb) //针对获取所有群组及成员列表回调处理
            {
                self.contactGroupCb(NO);
            }
            return YES;
        }else if ([iq.elementID isEqualToString:@"deleteGroupId:"]){
            //删除某个群组error回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSString *group_id = [[group elementForName:@"delete"] attributeStringValueForName:@"group_id"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            //删除某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(deleteGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate deleteGroupIdRspState:Group_Failure groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",nil];
                //删除群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupDeleteNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID isEqualToString:@"updateGroupId:groupDesc:ispublic"]){
            //更新某个群组error回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSString *group_name = [[group elementForName:@"create"] attributeStringValueForName:@"group_name"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            //更新某个群组error回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(updateGroupIdRspState:chatGroup:error:)])
            {
                [xmppGroupDelegate updateGroupIdRspState:Group_Failure chatGroup:nil error:errorCode];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_name,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"inviteGroupMember"]){
            //在某个群组中邀请加入群error回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *invite = [group elementForName:@"invite"];
            
            NSString *group_id = [invite attributeStringValueForName:@"group_id"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            //更新某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(inviteGroupMemberRspState:groupId:error:)])
            {
                [xmppGroupDelegate inviteGroupMemberRspState:Group_Failure groupId:group_id error:errorCode];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupInviteGroupMemberNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"kickoffGroupMember"]){
            //踢人离开群组 即删除群组成员后的error回应
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            NSString *group_id = [iq.elementID pathExtension];
           
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(kickoffGroupMemberRspState:groupId:errorMsg:)])
            {
                [xmppGroupDelegate kickoffGroupMemberRspState:Group_Failure groupId:group_id errorMsg:errorCode];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",
                                           nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupDeleteGroupMemberNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"requestJoinGroupId"]){
            //申请加入群组 后的error回应
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            NSString *group_id = [iq.elementID pathExtension];
            
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(requestJoinGroupIdRspState:groupId:errorMsg:)])
            {
                [xmppGroupDelegate requestJoinGroupIdRspState:Group_Failure groupId:group_id errorMsg:errorCode];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",
                                           nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupLeaveGroupNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"quitGroupId"]){
            //退出某个群组中error回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *quit_group = [group elementForName:@"quit_group"];
            
            NSString *group_id = [quit_group attributeStringValueForName:@"group_id"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            //退出某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(quitGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate quitGroupIdRspState:Group_Failure groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           errorCode,@"ErrorCode",nil];

                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupQuitGroupNotifaction object:notifiDic];
            }
            return YES;
        }//移交管理员权限后的error回应
        else if ([iq.elementID hasPrefix:@"abdicateAdmininstrationGroupId"])
        {
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *set_admin = [group elementForName:@"set_admin"];
            
            NSString *group_id = [set_admin attributeStringValueForName:@"group_id"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            
            //移交管理员权限回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(abdicateAdmininstrationGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate abdicateAdmininstrationGroupIdRspState:Group_Failure groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State", errorCode,@"ErrorCode",
                                           nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
            }
            return YES;
        }
        //修改自己在群组的昵称error回应
        else if ([iq.elementID hasPrefix:@"setGroupNickname"])
        {
            //            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            //            NSXMLElement *nickname = [group elementForName:@"nickname"];
            
            NSString *group_id = [iq.elementID pathExtension];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            //修改自己在群组的昵称
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(setGroupNicknameRspState:inGroupId:)])
            {
                [xmppGroupDelegate setGroupNicknameRspState:Group_Failure inGroupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State", errorCode,@"ErrorCode",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupQuitGroupNotifaction object:notifiDic];
            }
            return YES;
        }
         else if ([iq.elementID hasPrefix:@"acceptGroupInvite"]){
            //接收他人的邀请加入群组error回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *allow_apply = [group elementForName:@"allow_apply"];
            
            NSString *group_id = [allow_apply attributeStringValueForName:@"group_id"];
            NSString *jid = [allow_apply attributeStringValueForName:@"jid"];
            
            NSXMLElement *error = [iq elementForName:@"error"];
            NSString *errorCode = [error attributeStringValueForName:@"code"];
            //接收他人的邀请加入群组
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(acceptGroupMemberIdRspState:memberId:joinGroupId:)])
            {
                [xmppGroupDelegate acceptGroupMemberIdRspState:Group_Failure memberId:jid joinGroupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State", errorCode,@"ErrorCode",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupAcceptJoinNotifaction object:notifiDic];
            }
            return YES;
        }
         else if ([iq.elementID hasPrefix:@"rejectGroupMemberId"])
         {
             NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
             NSXMLElement *deny_apply = [group elementForName:@"deny_apply"];
             
             NSString *group_id = [deny_apply attributeStringValueForName:@"group_id"];
             NSString *jid = [deny_apply attributeStringValueForName:@"jid"];
             
             NSXMLElement *error = [iq elementForName:@"error"];
             NSString *errorCode = [error attributeStringValueForName:@"code"];
             //拒绝他人的邀请加入群组
             if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(rejectGroupMemberIdRspState:memberId:joinGroupId:)])
             {
                 [xmppGroupDelegate rejectGroupMemberIdRspState:Group_Failure memberId:jid joinGroupId:group_id];
             }
             else
             {
                 NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                            group_id,@"GroupId",
                                            @"fail",@"State", errorCode,@"ErrorCode",
                                            nil];
                 
                 [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupRejectJoinNotifaction object:notifiDic];
             }
             return YES;
         }
        NSXMLElement *query = [iq elementForName:@"query" xmlns:@"jabber:iq:register"];
        if (query == nil) {
            query = [iq elementForName:@"query" xmlns:@"jabber:iq:auth"];
        }
        NSLog(@"%@",query.xmlns );
        NSXMLElement *error = [iq elementForName:@"error"];
        NSString *code = [error attributeStringValueForName:@"code"];
        NSLog(@"didReceiveIQ errorCode= %@",code );
        if ([query.xmlns isEqualToString:@"jabber:iq:register"])
        {
            [self deleteXmppRecordReqId:@"registerNewAccount"];
            if ([code isEqualToString:@"409"])
            {
                //已经注册
                if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
                {
                    [xmppLogRegDelegate registerNewAccountRspState:register_HaveRegisterd username:logRegWxUserObject.UserId password:logRegWxUserObject.UserPassword];
                    [self disconnect]; //vince
                }
            }
            else
            {
                //注册失败
                if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
                {
                    [xmppLogRegDelegate registerNewAccountRspState:register_Fail username:logRegWxUserObject.UserId password:logRegWxUserObject.UserPassword];
                    loginOrRegState = register_Fail;
                }
                [self disconnect];
            }
            return YES;
        }
        if ([query.xmlns isEqualToString:@"jabber:iq:auth"])
        {
            [self deleteXmppRecordReqId:@"loginWithUserId"];
            
            loginOrRegState = login_Fail;
            
            {//保存登录用户信息
                [ChatLoginUserMgr saveChatLoginUser:logRegWxUserObject];
            }
            
            WXLog(@"此用户验证失败，请重新登陆！！！！！");
            
            //用户登录失败
            if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
            {
                NSString *errordescribe = [NSString stringWithFormat:@"error:%@",code];
                NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                           [Utility getBareContactId:logRegWxUserObject.UserId], @"userid", logRegWxUserObject.UserPassword, @"password",
                                           @"用户验证失败", @"describe",
                                           errordescribe,@"errorCode",nil];
                [xmppLogRegDelegate loginWithUserIdRspState:login_Fail loginInfo:loginInfo];
            }
            [self disconnect];
        }

        return YES;
    }
    
    
#pragma mark---------iq返回result结果--------
    if ([@"result" isEqualToString:iq.type])
    {
        /**消息免打扰设置*/
        if ([iq.elementID hasPrefix:@"messageTroubleget"]) {
            //创建群组返回数据result
            NSXMLElement *item = [iq elementForName:@"dnd" xmlns:@"urn:xmpp:dnd"];
            BOOL istro = [item attributeBoolValueForName:@"dnd"];
            [[NSNotificationCenter defaultCenter]postNotificationName:KXmppMessageTroubleNoti object:@(istro)];
        }
        /**删除聊天记录*/
        if ([iq.elementID hasPrefix:@"deletemessage"]) {
            
        }
        if ([iq.elementID isEqualToString:@"Register_ID"])
        {
            [self deleteXmppRecordReqId:@"registerNewAccount"];
            //注册成功
            if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
            {
                [xmppLogRegDelegate registerNewAccountRspState:register_OK username:logRegWxUserObject.UserId password:logRegWxUserObject.UserPassword];
                loginOrRegState = register_OK;
                [self disconnect]; //vince
            }
            return YES;
        }
        else if ([iq.elementID isEqualToString:@"Login_ID"]){
            isLoginSuccess = YES;
            [self deleteXmppRecordReqId:@"loginWithUserId"];
            
            if (isReConnecting) //99999999999999
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconnSucc object:nil];
                isReConnecting = NO;
                return YES;
            }
            
            {//保存登录用户信息
                [ChatLoginUserMgr saveChatLoginUser:logRegWxUserObject];
                
                //检查异常发送失败保存的状态异常问题
                [ChatMessageMgr checkMessageListAllState];
            }
            
            [[IWxChatMgrGroup sharedGroup] initAllContactGroups];//登录成功直接获取我的群组信息
            
            NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [Utility getBareContactId:logRegWxUserObject.UserId], @"userid", logRegWxUserObject.UserPassword, @"password",
                                       @"用户登录成功", @"describe",nil];
            
            //用户登录成功
            WXLog(@"此用户已经通过验证，登陆成功！1111111！");
            if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
            {
                [xmppLogRegDelegate loginWithUserIdRspState:login_OK loginInfo:loginInfo];
            }
            if (self.completion) {
                self.completion(loginInfo, login_OK);
            }
            loginOrRegState = login_OK;
            
            
            
            [self ucfgroup_uploadDeviceToken:self.deviceToken owner:self.logRegWxUserObject.UserId];
            
            //发送登录成功消息通知
            [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPLoginSuccessNotifaction object:@"登录成功"];
            //登录成功时，再启动ping
            [self autoPingProxyServer:kXMPPmyHostAddr];
            return YES;
        }
#pragma mark---------联系人相关result-------
        //删除联系人返回result
        if ([iq.elementID hasPrefix:@"ucfgroup_removeBuddy"])
        {
            NSString *nameJid = [iq.elementID pathExtension];
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(removeContactRsp:contactId:errorState:)])
            {
                [xmppContactDelegate removeContactRsp:Contact_Success contactId:nameJid errorState:Contact_NoError];
            }
            return YES;
        }
        //修改备注---昵称result
        else if ([iq.elementID hasPrefix:@"ucfgroup_setNickname"])
        {
            NSString *nameJid = [iq.elementID pathExtension];
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(remarkContactRsp:contactId:errorState:)])
            {
                [xmppContactDelegate remarkContactRsp:Contact_Success contactId:nameJid errorState:Contact_NoError];
            }
            return YES;
        }
        else if ([iq.elementID hasPrefix:@"ucfgroup_CreateGroupName"]){
            //创建群组返回数据result
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *create = [group elementForName:@"create"];
            NSString *group_id = [create attributeStringValueForName:@"group_id"];
            
            NSString *pre_group_id = iq.elementID; //预保存的群Id
            
            ChatGroup *readObj = [ChatGroupMgr readChatGroupMsgbyGroupId:pre_group_id];
            {
                NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                [chatGroupDic setValue:group_id forKey:@"group_id"];
                [chatGroupDic setValue:readObj.group_name forKey:@"group_name"];
                [chatGroupDic setValue:readObj.group_public forKey:@"group_public"];
                [chatGroupDic setValue:readObj.group_approval forKey:@"group_approval"];
                [chatGroupDic setValue:readObj.group_desc forKey:@"group_desc"];
                [chatGroupDic setValue:readObj.group_createTime forKey:@"group_createTime"];
                [chatGroupDic setValue:readObj.group_membersMax forKey:@"group_membersMax"];
                
                [ChatGroupMgr deleteGroupListByGroupId:pre_group_id];
                [ChatGroupMgr saveChatGroupDic:chatGroupDic];
                
                [ChatGroupMgr deleteGroupBackUpByGroupId:pre_group_id];
                [ChatGroupMgr saveChatGroupBackUpDic:chatGroupDic];
                
                //将自己创建者owner 信息 保存到成员表ChatGroupMember中
                {
                    ChatLoginUser *ownerLogin = [ChatLoginUserMgr getCurLoginUser];
                    NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
                    [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
                    [chatGroupMemberDic setValue:@"owner" forKey:@"member_affiliations"];
                    [chatGroupMemberDic setValue:[Utility getBareContactId:ownerLogin.UserId] forKey:@"member_nickname"];
                    [chatGroupMemberDic setValue:[Utility getBareContactId:ownerLogin.UserId] forKey:@"member_id"];
                    
                    [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
                }
            }
            
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(creatGroupNameRspState:groupId:withMsg:)])
            {
                [xmppGroupDelegate creatGroupNameRspState:Group_Success groupId:group_id withMsg:readObj.group_name];
            }
            return YES;
        }else if ([iq.elementID isEqualToString:@"initAllContactGroups"]){
            //初始化群组并获取所有群列表和群成员列表result回应
            WXLog(@"initAllContactGroups");
            
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            BOOL replaceGroupListFlag = [[group attributeStringValueForName:@"replace"] boolValue];
            if (replaceGroupListFlag) {
                [ChatGroupMgr deleteAllGroupList];
            }
            
            NSXMLElement *get_group = [group elementForName:@"get_group"];
            
            //---vince@2014-10-22
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[get_group attributeStringValueForName:@"ver"] forKey:@"GroupVer"];
            [defaults synchronize];
            
            NSArray *get_groupArray = [get_group children];
            NSInteger get_groupArrayCount = [get_groupArray count];
            WXLog(@"get_groupArrayCount= %d",(int)get_groupArrayCount);
            
            for (NSXMLElement *groupitem in get_groupArray)
            {
                BOOL replaceGroupMemberFlag = [[groupitem attributeStringValueForName:@"replace"] boolValue];
                
                NSString *group_id = [groupitem attributeStringValueForName:@"group_id"];
                NSString *group_name = [groupitem attributeStringValueForName:@"group_name"];
                NSString *public = [groupitem attributeStringValueForName:@"public"];
                NSString *approval = [groupitem attributeStringValueForName:@"approval"];
                NSString *desc = [groupitem attributeStringValueForName:@"desc"];
                NSString *create_time = [groupitem attributeStringValueForName:@"create_time"];
                NSString *members_max = [groupitem attributeStringValueForName:@"members_max"];
                
                if (replaceGroupMemberFlag) {
                    [ChatGroupMgr deleteAllGroupMemberByGroupId:group_id];
                }
                
                {
                    NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                    [chatGroupDic setValue:group_id forKey:@"group_id"];
                    [chatGroupDic setValue:group_name forKey:@"group_name"];
                    [chatGroupDic setValue:public forKey:@"group_public"];
                    [chatGroupDic setValue:approval forKey:@"group_approval"];
                    [chatGroupDic setValue:desc forKey:@"group_desc"];
                    [chatGroupDic setValue:create_time forKey:@"group_createTime"];
                    [chatGroupDic setValue:members_max forKey:@"group_membersMax"];
                    
                    [ChatGroupMgr saveChatGroupDic:chatGroupDic];
                    [ChatGroupMgr saveChatGroupBackUpDic:chatGroupDic];

                }
                
                NSArray *memberArray = [groupitem children];
                //NSUInteger memberCount = [memberArray count];
                //WXLog(@"memberCount= %lu",(unsigned long)memberCount);
                for (NSXMLElement *item in memberArray)
                {
                    NSString *affiliations = [item attributeStringValueForName:@"affiliations"];
                    NSString *nickname = [item attributeStringValueForName:@"nickname"];
                    NSString *jid = [Utility getBareContactId:[item attributeStringValueForName:@"jid"]];
                    {
                        NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
                        [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
                        [chatGroupMemberDic setValue:affiliations forKey:@"member_affiliations"];
                        [chatGroupMemberDic setValue:nickname forKey:@"member_nickname"];
                        [chatGroupMemberDic setValue:jid forKey:@"member_id"];
                        
                        [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
                    }
                }
            }
            
            if (self.contactGroupCb) //针对获取所有群组及成员列表回调处理
            {
                self.contactGroupCb(YES);
            }
            
            NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                       @"All group",@"GroupId",
                                       @"success",@"State",
                                       @"0",@"ErrorCode",nil];
            //更新群组结果通知
            [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
            
            return YES;
        }else if ([iq.elementID isEqualToString:@"deleteGroupId:"]){
            //删除某个群组result回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *delete = [group elementForName:@"delete"];
            NSString *group_id = [delete attributeStringValueForName:@"group_id"];
            [ChatGroupMgr deleteGroupListByGroupId:group_id]; //删除数据库中的群
            //删除某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(deleteGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate deleteGroupIdRspState:Group_Success groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"success",@"State",nil];
                //删除群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupDeleteNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID isEqualToString:@"updateGroupId:groupDesc:ispublic"]){
            //更新某个群组result回应
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *create = [group elementForName:@"create"];
            NSString *group_id = [create attributeStringValueForName:@"group_id"];
            
            ChatGroup *readObj = [ChatGroupMgr readChatGroupMsgbyGroupId:group_id];
            //更新某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(updateGroupIdRspState:chatGroup:error:)])
            {
                [xmppGroupDelegate updateGroupIdRspState:Group_Success chatGroup:readObj error:nil];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"fail",@"State",
                                           readObj,@"ChatGroupObj",nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
            }
            return YES;
        }else if ([iq.elementID hasPrefix:@"inviteGroupMember"]){
            //在某个群组中邀请加入群result回应
 //           NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
 //           NSXMLElement *invite = [group elementForName:@"invite"];
            
            NSString *group_id = [iq.elementID pathExtension];
            //更新某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(inviteGroupMemberRspState:groupId:error:)])
            {
                [xmppGroupDelegate inviteGroupMemberRspState:Group_Success groupId:group_id error:nil];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupInviteGroupMemberNotifaction object:notifiDic];
            }
            return YES;
        }
        
        else if ([iq.elementID hasPrefix:@"kickoffGroupMember"]){
            //踢人离开群组 即删除群组成员后的result回应
            //NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            //NSXMLElement *delete_member = [group elementForName:@"delete_member"];
            
            NSString *group_id = [iq.elementID pathExtension];
#warning message - 群主踢人操作－－不需要删除群表中的数据
//            [ChatGroupMgr deleteGroupListByGroupId:group_id]; //删除数据库中的群

            //删除群组成员结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(kickoffGroupMemberRspState:groupId:errorMsg:)])
            {
                [xmppGroupDelegate kickoffGroupMemberRspState:Group_Success groupId:group_id errorMsg:nil];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                //更新群组结果通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupDeleteGroupMemberNotifaction object:notifiDic];
            }
            return YES;
        }
        //申请加入群组 后的result回应
        else if ([iq.elementID hasPrefix:@"requestJoinGroupId"])
        {
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *invite = [group elementForName:@"invite"];
            
            NSString *group_id = [iq.elementID pathExtension];
            
            NSArray *listArray = invite.children;
            for (NSXMLElement *user in listArray) {
                //NSString *jid = [user attributeStringValueForName:@"jid"];
                NSString *result = [user attributeStringValueForName:@"result"];
                //解释：result=1表示邀请成功，result=0表示此用户不存在
                if ([result isEqualToString:@"1"])
                {
                    //删除群组成员结果回调
                    if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(requestJoinGroupIdRspState:groupId:errorMsg:)])
                    {
                        [xmppGroupDelegate requestJoinGroupIdRspState:Group_Success groupId:group_id errorMsg:nil];
                    }
                    else
                    {
                        NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                   group_id,@"GroupId",
                                                   @"sucess",@"State",
                                                   nil];
                        //更新群组结果通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupLeaveGroupNotifaction object:notifiDic];
                    }
                }
                else if ([result isEqualToString:@"0"])
                {
                    //删除群组成员结果回调
                    if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(requestJoinGroupIdRspState:groupId:errorMsg:)])
                    {
                        [xmppGroupDelegate requestJoinGroupIdRspState:Group_Failure groupId:group_id errorMsg:@"用户不存在"];
                    }
                    else
                    {
                        NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                   group_id,@"GroupId",
                                                   @"fail",@"State",
                                                   @"用户不存在",@"ErrorCode",nil];
                        //更新群组结果通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupLeaveGroupNotifaction object:notifiDic];
                    }
                }
            }
            
            return YES;
        }
        
        //移交管理员权限后的result回应
        else if ([iq.elementID hasPrefix:@"abdicateAdmininstrationGroupId"])
        {
            // NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            // NSXMLElement *set_admin = [group elementForName:@"set_admin"];
            
            NSString *group_id = nil,*adminJid = nil;
            NSString *extContent = [iq.elementID substringFromIndex:[@"abdicateAdmininstrationGroupId." length]];
            NSArray *listA = [extContent componentsSeparatedByString:@"="];
            for (int i=0; i<listA.count; i++) {
                if (i==0) {
                    group_id = [listA objectAtIndex:i];
                }
                if (i==1) {
                    adminJid = [Utility getBareContactId:[listA objectAtIndex:i]];
                }
            }
            
            ChatGroupMember *readObj = [ChatGroupMgr readGroupMemberByGroupId:group_id withMemberId:[Utility getBareContactId:self.logRegWxUserObject.UserId]];
            NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
            [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
            [chatGroupMemberDic setValue:@"member" forKey:@"member_affiliations"];
            [chatGroupMemberDic setValue:readObj.member_nickname forKey:@"member_nickname"];
            [chatGroupMemberDic setValue:readObj.member_id forKey:@"member_id"];
            [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
            
            readObj = [ChatGroupMgr readGroupMemberByGroupId:group_id withMemberId:adminJid];
            [chatGroupMemberDic setValue:@"owner" forKey:@"member_affiliations"];
            [chatGroupMemberDic setValue:readObj.member_nickname forKey:@"member_nickname"];
            [chatGroupMemberDic setValue:readObj.member_id forKey:@"member_id"];
            [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
            
            
            //移交管理员权限回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(abdicateAdmininstrationGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate abdicateAdmininstrationGroupIdRspState:Group_Success groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
            }
            return YES;
        }

        else if ([iq.elementID hasPrefix:@"quitGroupId"]){
            //退出群组的result回应
//            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            // NSXMLElement *quit_group = [group elementForName:@"quit_group"];
            
            NSString *group_id = [iq.elementID pathExtension];
            
            //删除本地群及群成员
            [ChatGroupMgr deleteAllGroupMemberByGroupId:group_id];
            [ChatGroupMgr deleteGroupListByGroupId:group_id];
            
            //退出某个群组结果回调
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(quitGroupIdRspState:groupId:)])
            {
                [xmppGroupDelegate quitGroupIdRspState:Group_Success groupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupQuitGroupNotifaction object:notifiDic];
            }
            return YES;
        }   //修改自己在群组的昵称result回应
        else if ([iq.elementID hasPrefix:@"setGroupNickname"])
        {
            //            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            // NSXMLElement *nickname = [group elementForName:@"nickname"];
            
            NSString *group_id = [iq.elementID pathExtension];
            //修改自己在群组的昵称
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(setGroupNicknameRspState:inGroupId:)])
            {
                [xmppGroupDelegate setGroupNicknameRspState:Group_Success inGroupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupQuitGroupNotifaction object:notifiDic];
            }
            return YES;
        }
        else if ([iq.elementID hasPrefix:@"acceptGroupInvite"]){
             //接收他人的邀请加入群组result回应
//            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
//            NSXMLElement *allow_apply = [group elementForName:@"allow_apply"];
//            
//            NSString *group_id = [allow_apply attributeStringValueForName:@"group_id"];
//            NSString *jid = [allow_apply attributeStringValueForName:@"jid"];
            
            NSString *group_id = [iq.elementID pathExtension];
            //接收他人的邀请加入群组
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(acceptGroupMemberIdRspState:memberId:joinGroupId:)])
            {
                [xmppGroupDelegate acceptGroupMemberIdRspState:Group_Success memberId:nil joinGroupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"sucess",@"State",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupAcceptJoinNotifaction object:notifiDic];
            }
            return YES;
        }
        //拒绝他人的邀请加入群组result回应
        else if ([iq.elementID hasPrefix:@"rejectGroupMemberId"])
        {
            //            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            //            NSXMLElement *deny_apply = [group elementForName:@"deny_apply"];
            //
            //            NSString *group_id = [deny_apply attributeStringValueForName:@"group_id"];
            //            NSString *jid = [deny_apply attributeStringValueForName:@"jid"];
            
            NSString *group_id = [iq.elementID pathExtension];
            //拒绝他人的邀请加入群组
            if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(rejectGroupMemberIdRspState:memberId:joinGroupId:)])
            {
                [xmppGroupDelegate rejectGroupMemberIdRspState:Group_Success memberId:nil joinGroupId:group_id];
            }
            else
            {
                NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           group_id,@"GroupId",
                                           @"success",@"State",
                                           nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupRejectJoinNotifaction object:notifiDic];
            }
            return YES;
        }
    }
#pragma mark--*******获取好友列表******目前没有处理 －－
    
    
#pragma mark---------iq返回push---set-----
    else if ([@"set" isEqualToString:iq.type]) //id="push
    {
        NSXMLElement *query = iq.childElement;
        //如下Case处理群组Push通知相关
        if ([query.xmlns isEqualToString:@"http://www.ucfgroup.com/protocol/group"])
        {
            //---vince@2014-10-22
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[query attributeStringValueForName:@"ver"] forKey:@"GroupVer"];
            [defaults synchronize];
            
            //邀请好友Case 收到push
            NSXMLElement *get_group = [query elementForName:@"get_group"];
            if(get_group != nil)
            {
                NSArray *get_groups = [get_group children];
                if ([get_groups count] > 0) {
                    for (NSXMLElement *groupitem in get_groups)
                    {
                        BOOL replaceGroupMemberFlag = [[groupitem attributeStringValueForName:@"replace"] boolValue];
                        
                        NSString *group_id = [groupitem attributeStringValueForName:@"group_id"];
                        NSString *group_name = [groupitem attributeStringValueForName:@"group_name"];
                        NSString *public = [groupitem attributeStringValueForName:@"public"];
                        NSString *approval = [groupitem attributeStringValueForName:@"approval"];
                        NSString *desc = [groupitem attributeStringValueForName:@"desc"];
                        NSString *create_time = [groupitem attributeStringValueForName:@"create_time"];
                        NSString *members_max = [groupitem attributeStringValueForName:@"members_max"];
                        
                        if (replaceGroupMemberFlag) {
                            [ChatGroupMgr deleteAllGroupMemberByGroupId:group_id];
                        }
                        else
                        {
                            {
                                NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                                [chatGroupDic setValue:group_id forKey:@"group_id"];
                                [chatGroupDic setValue:group_name forKey:@"group_name"];
                                [chatGroupDic setValue:public forKey:@"group_public"];
                                [chatGroupDic setValue:approval forKey:@"group_approval"];
                                [chatGroupDic setValue:desc forKey:@"group_desc"];
                                [chatGroupDic setValue:create_time forKey:@"group_createTime"];
                                [chatGroupDic setValue:members_max forKey:@"group_membersMax"];
                                
                                [ChatGroupMgr saveChatGroupDic:chatGroupDic];
                                [ChatGroupMgr saveChatGroupBackUpDic:chatGroupDic];

                            }
                        }
                        
                        NSArray *memberArray = [groupitem children];
                        NSUInteger memberCount = [memberArray count];
                        WXLog(@"memberCount= %ld",(long)memberCount);
                        for (NSXMLElement *item in memberArray)
                        {
                            NSString *affiliations = [item attributeStringValueForName:@"affiliations"];
                            NSString *nickname = [item attributeStringValueForName:@"nickname"];
                            NSString *jid = [item attributeStringValueForName:@"jid"];
                            BOOL member_deleteFlag = [[item attributeStringValueForName:@"delete"] boolValue];
                            {
                                NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
                                [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
                                [chatGroupMemberDic setValue:affiliations forKey:@"member_affiliations"];
                                [chatGroupMemberDic setValue:nickname forKey:@"member_nickname"];
                                [chatGroupMemberDic setValue:[Utility getBareContactId:jid] forKey:@"member_id"];
                                
                                if (member_deleteFlag)
                                {
                                    [ChatGroupMgr deleteGroupMemberGroupId:group_id withMemberId:[Utility getBareContactId:jid]];
                                    
                                    //更新群组结果通知
                                    [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:nil];
                                }
                                else
                                {
                                    [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
                                }
                            }
                        }
                    }
                }
                
                return YES;
            }
            
            //更新群组Push
            BOOL deleteFlag = [query attributeBoolValueForName:@"delete"];
            NSXMLElement *group = [query elementForName:@"group"];
            if (deleteFlag && group)
            {
                NSString *group_id = [group attributeStringValueForName:@"group_id"];
//                [ChatGroupMgr deleteGroupListByGroupId:group_id];
                [ChatGroupMgr deleteAllGroupMemberByGroupId:group_id];//删除对应的群成员列表
            }
            else
            {
                NSString *group_id = [group attributeStringValueForName:@"group_id"];
                NSString *group_name = [group attributeStringValueForName:@"group_name"];
                NSString *public = [group attributeStringValueForName:@"public"];
                NSString *approval = [group attributeStringValueForName:@"approval"];
                NSString *desc = [group attributeStringValueForName:@"desc"];
                NSString *create_time = [group attributeStringValueForName:@"create_time"];
                NSString *members_max = [group attributeStringValueForName:@"members_max"];
                {
                    NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                    [chatGroupDic setValue:group_id forKey:@"group_id"];
                    [chatGroupDic setValue:group_name forKey:@"group_name"];
                    [chatGroupDic setValue:public forKey:@"group_public"];
                    [chatGroupDic setValue:approval forKey:@"group_approval"];
                    [chatGroupDic setValue:desc forKey:@"group_desc"];
                    [chatGroupDic setValue:create_time forKey:@"group_createTime"];
                    [chatGroupDic setValue:members_max forKey:@"group_membersMax"];
                    
                    [ChatGroupMgr updateChatGroupDic:chatGroupDic];
                    [ChatGroupMgr updateChatGroupBackUpDic:chatGroupDic];
                }
            }
            
        }
        //更新某个群组set-Push回应 ----暂时走上面通用Case ----fusuwei
        else if ([iq.elementID isEqualToString:@"updateGroupId:groupDesc:ispublic"])
        {
            NSXMLElement *group = [iq elementForName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            {
                NSString *group_id = [group attributeStringValueForName:@"group_id"];
                NSString *group_name = [group attributeStringValueForName:@"group_name"];
                NSString *public = [group attributeStringValueForName:@"public"];
                NSString *approval = [group attributeStringValueForName:@"approval"];
                NSString *desc = [group attributeStringValueForName:@"desc"];
                NSString *create_time = [group attributeStringValueForName:@"create_time"];
                NSString *members_max = [group attributeStringValueForName:@"members_max"];
                {
                    NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                    [chatGroupDic setValue:group_id forKey:@"group_id"];
                    [chatGroupDic setValue:group_name forKey:@"group_name"];
                    [chatGroupDic setValue:public forKey:@"group_public"];
                    [chatGroupDic setValue:approval forKey:@"group_approval"];
                    [chatGroupDic setValue:desc forKey:@"group_desc"];
                    [chatGroupDic setValue:create_time forKey:@"group_createTime"];
                    [chatGroupDic setValue:members_max forKey:@"group_membersMax"];
                    
                    [ChatGroupMgr updateChatGroupDic:chatGroupDic];
                    [ChatGroupMgr updateChatGroupBackUpDic:chatGroupDic];

                }
            }
        }
        else if ([@"query" isEqualToString:query.name])
        {
            NSArray *items = [query children];
            for (NSXMLElement *item in items)
            {
                NSString *subscription = [item attributeStringValueForName:@"subscription"];
                NSString *ask = [item attributeStringValueForName:@"ask"];
                
                NSString *jid = [Utility getBareContactId:[item attributeStringValueForName:@"jid"]];
                //根据6121协议，在修改备注名称后，才会有name字段
                NSString *name = [item attributeStringValueForName:@"name"];
                
                //主动邀请回应ACK跑此Case
                if ([subscription isEqualToString:@"none"])
                {
                    NSMutableDictionary *contactObjDic = [[NSMutableDictionary alloc] init];
                    [contactObjDic setObject:jid forKey:@"ContactId"];
                    if (name == nil) {
                        [contactObjDic setObject:jid forKey:@"ContactName"];
                    }
                    else
                    {
                        [contactObjDic setObject:name forKey:@"ContactName"];
                    }
           
                    if ([ask isEqualToString:@"delete"]) //删除好友服务器返回Push处理
                    {
                        [ChatContactMgr deleteContactId:jid];
                        //发送用户好友列表改变通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPBuddyListChangeNotifaction object:contactObjDic];
                    }
                    //ask 有值表示是 请求添加好友    2---out--请求添加好友--主动发起添加好友   3--in--被邀请
                    else if ([ask isEqualToString:@"out"])
                    {
                        [contactObjDic setObject:NotDoing forKey:@"ContactState"];
                        [contactObjDic setObject:[NSNumber numberWithBool:YES] forKey:@"ContactIsSend"];
                        [ChatContactMgr saveChatContactRequestDic:contactObjDic];
                    }
                    else
                    {
                        [contactObjDic setObject:NotDoing forKey:@"ContactState"];
                        [contactObjDic setObject:[NSNumber numberWithBool:NO] forKey:@"ContactIsSend"];
                        [ChatContactMgr saveChatContactRequestDic:contactObjDic];
                    }
                }
                else if ([subscription isEqualToString:@"both"]) //点击接收同意对方请求后，添加进入好友
                {
                    NSMutableDictionary *contactObjDic = [[NSMutableDictionary alloc] init];
                    [contactObjDic setObject:jid forKey:@"ContactId"];

                    if (name == nil) {
                        [contactObjDic setObject:jid forKey:@"ContactName"];
                    }
                    else
                    {
                        [contactObjDic setObject:name forKey:@"ContactName"];
                    }
                    
                    [contactObjDic setObject:@"已是好友" forKey:@"ContactState"];
                    
                    {
                        ChatContactRequest *findObj = [ChatContactMgr fetchChatRequestByContactId:jid];
                        if (findObj) {
                            //更新请求表
                            [ChatContactMgr saveUpdateChatContactRequestContactId:jid fieldName:@"ContactState" value:Bothbuddy];
                        }
                        else
                        {
                            //更新请求表
                            [ChatContactMgr saveUpdateChatContactRequestContactId:jid fieldName:@"ContactState" value:AgreeReq];
                        }
                    }
                    
                    //保存联系人到ChatContact表中
                    [ChatContactMgr saveChatContactDic:contactObjDic];
                    
                    
                    
                    //发送用户好友列表改变通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPBuddyListChangeNotifaction object:contactObjDic];
                    
                    if(xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(didAcceptedByContact:)])
                    {
                        [xmppContactDelegate didAcceptedByContact:jid];
                    }
                }

            }
        }
    }
#pragma mark -Ping
    /***************************************3333********************************/
    if (iq.isGetIQ)
    {
        //解析iq 是ping类型则给openfier 响应一个IQ
        NSXMLElement *query = iq.childElement;
        
        if ([@"ping" isEqualToString:query.name])
        {
            //服务器会在给定的时间内向客户端发送ping包（用来确认客户端用户是否在线）,当第二次发送bing包时，如果客户端无响应则会T用户下线
            //urn:xmpp:ping(new) jabber:client(old)
            NSXMLElement *ping = [NSXMLElement elementWithName:@"ping" xmlns:@"urn:xmpp:ping"];
            
            NSXMLElement *pingIq = [NSXMLElement elementWithName:@"iq"];
            
            XMPPJID *myJID = xmppStream.myJID;
            [pingIq addAttributeWithName:@"from" stringValue:myJID.description];
            [pingIq addAttributeWithName:@"to" stringValue:myJID.domain];
            [pingIq addAttributeWithName:@"type" stringValue:@"get"];
            [pingIq addAttributeWithName:@"xmlns" stringValue:@"jabber:client"];
            [pingIq addAttributeWithName:@"id" stringValue:iq.elementID];

            [pingIq addChild:ping];
            
            //发送的iq可以不做任何的设置
            [xmppStream sendElement:pingIq];
        }
        
        return YES;
    }
    
    return YES;
}

#pragma mark --------收到消息 didReceiveMessage -----------
//收到消息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
//    NSLog(@"收到message： %@",message);

    
    
    NSString *fromStr = [[message attributeForName:@"from"] stringValue];
    NSArray *fromArray = [fromStr componentsSeparatedByString:@"@"];
    NSString *from = fromArray[0];
    NSArray *fromNameArray = [from componentsSeparatedByString:@"/"];
    NSString *fromName = from;//通知栏显示的名称
    if (fromNameArray.count) {
        fromName = fromNameArray[0];
        
    }
    //    NSString *from = [[message from] bare]; //[[message attributeForName:@"from"] stringValue];
    NSString *toStr = [[message attributeForName:@"to"] stringValue];
    NSArray *toArray = [toStr componentsSeparatedByString:@"/"];
    NSString *to = toArray[0];
    
    __block NSString *messageId = [[message attributeForName:@"id"] stringValue];
    /**如果messageid 为空 取archived 标签里面的*/
    if (messageId== nil) {
        
        NSXMLElement *archived = [message elementForName:@"archived" xmlns:@"urn:xmpp:mam:tmp"];
        messageId = [[archived attributeForName:@"id"] stringValue];
    }
    
    //发送消息收到服务器返回接收Ack消息
    NSXMLElement *received = [message elementForName:@"received" xmlns:@"urn:xmpp:receipts"];
    if(received != nil)
    {
        NSString *received_id = [[received attributeForName:@"id"] stringValue];
        
        WXLog(@"=================received======messageId= %@",messageId);
        
        [self deleteXmppRecordReqId:received_id];
        
        NSString *error = [received attributeStringValueForName:@"error"];
        if (error)
        {
        }
        
        NSString *created_at = [[message attributeForName:@"created_at"] stringValue];

        [ChatMessageMgr saveUpdateMessageId:messageId fieldName:@"createTime" value:created_at];
        
        //表示是服务器收到发送消息的回应
        if ([from isEqualToString:kXMPPMyBareDomain] || [self findSubstring:kXMPPGroupDomain inString:from])
        {
            NSString *fromO = [[message attributeForName:@"from"] stringValue];
            
            
            if ([self findSubstring:[NSString stringWithFormat:@"%@%@", kXMPPGroupDomain, @"/"] inString:fromO])
            {
                [ChatMessageMgr saveUpdateMessageId:received_id fieldName:@"messageStatus" valueInt:Chat_Send_Success];
                
                //发送消息对方收到，通知应用层
                if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(didRecipientRecieved:recipientId:)])
                {
                    [self.xmppMsgDelegate didRecipientRecieved:received_id recipientId:to];
                }
                return;
            }
            
            [ChatMessageMgr saveUpdateMessageId:received_id fieldName:@"messageStatus" valueInt:Chat_Send_Success];
            //发送消息成功，通知应用层
            if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)])
            {
                //WXLog(@"====feebaa====");
                NSString *retPrmt = [NSString stringWithFormat:@"%@ %@",received_id,@"发送成功"];
                [self.xmppMsgDelegate sendMessageRspState:Chat_Send_Success messageId:received_id error:retPrmt];
            }
        }
        else
        {
            [ChatMessageMgr saveUpdateMessageId:received_id fieldName:@"messageStatus" valueInt:Chat_Receive_Success];
            
            //发送消息对方收到，通知应用层
            if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(didRecipientRecieved:recipientId:)])
            {
                [self.xmppMsgDelegate didRecipientRecieved:received_id recipientId:to];
            }
        }
        
        return;
    }

#pragma mark -----Message 收到 notice 处理-------
//    <message from="group.wx.com" to="langxw@wx.com">
//      <event xmlns="http://www.ucfgroup.com/protocol/group#event">
//          <items group_id="7">
//              <item notice="invite" from="jason@wx.com" nickname="Jason">您被邀请加入了组</item>
//          </items>
//      </event>
//    </message>
#pragma mark -  群聊提示消息，提示“您被邀请加入了组
    if ([from isEqualToString:kXMPPGroupDomain])
    {
        { //保存新群
            NSXMLElement *query = [message elementForName:@"query" xmlns:@"http://www.ucfgroup.com/protocol/group"];
            NSXMLElement *get_group = [query elementForName:@"get_group"];
            
            //---vince@2014-10-22
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[get_group attributeStringValueForName:@"ver"] forKey:@"GroupVer"];
            [defaults synchronize];
            
            NSArray *get_groupArray = [get_group children];
            NSInteger get_groupArrayCount = [get_groupArray count];
            WXLog(@"get_groupArrayCount= %d",(int)get_groupArrayCount);
            
            for (NSXMLElement *groupitem in get_groupArray)
            {
                BOOL replaceGroupMemberFlag = [[groupitem attributeStringValueForName:@"replace"] boolValue];
                
                NSString *group_id = [groupitem attributeStringValueForName:@"group_id"];
                NSString *group_name = [groupitem attributeStringValueForName:@"group_name"];
                NSString *public = [groupitem attributeStringValueForName:@"public"];
                NSString *approval = [groupitem attributeStringValueForName:@"approval"];
                NSString *desc = [groupitem attributeStringValueForName:@"desc"];
                NSString *create_time = [groupitem attributeStringValueForName:@"create_time"];
                NSString *members_max = [groupitem attributeStringValueForName:@"members_max"];
                
                if (replaceGroupMemberFlag) {
                    [ChatGroupMgr deleteAllGroupMemberByGroupId:group_id];
                }
                
                {
                    NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
                    [chatGroupDic setValue:group_id forKey:@"group_id"];
                    [chatGroupDic setValue:group_name forKey:@"group_name"];
                    [chatGroupDic setValue:public forKey:@"group_public"];
                    [chatGroupDic setValue:approval forKey:@"group_approval"];
                    [chatGroupDic setValue:desc forKey:@"group_desc"];
                    [chatGroupDic setValue:create_time forKey:@"group_createTime"];
                    [chatGroupDic setValue:members_max forKey:@"group_membersMax"];
                    
                    [ChatGroupMgr saveChatGroupDic:chatGroupDic];
                    [ChatGroupMgr saveChatGroupBackUpDic:chatGroupDic];

                }
                
                NSArray *memberArray = [groupitem children];
                NSUInteger memberCount = [memberArray count];
                WXLog(@"memberCount= %lu",(unsigned long)memberCount);
                for (NSXMLElement *item in memberArray)
                {
                    NSString *affiliations = [item attributeStringValueForName:@"affiliations"];
                    NSString *nickname = [item attributeStringValueForName:@"nickname"];
                    NSString *jid = [item attributeStringValueForName:@"jid"];
                    {
                        NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
                        [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
                        [chatGroupMemberDic setValue:affiliations forKey:@"member_affiliations"];
                        [chatGroupMemberDic setValue:nickname forKey:@"member_nickname"];
                        [chatGroupMemberDic setValue:[Utility getBareContactId:jid] forKey:@"member_id"];
                        
                        [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
                    }
                }
            }
        }
        
        NSXMLElement *event = [message elementForName:@"event" xmlns:@"http://www.ucfgroup.com/protocol/group#event"];
        if (event != nil)
        {
            NSXMLElement *items = [event elementForName:@"items"];
            NSString *group_id = [items attributeStringValueForName:@"group_id"];
            
            {
                NSXMLElement *item = [items elementForName:@"item"];
                NSString *notice = [item attributeStringValueForName:@"notice"];
                NSString *from = [item attributeStringValueForName:@"from"];
                NSString *nickname = [item attributeStringValueForName:@"nickname"];
                NSString *msg = [item stringValue];
                
                {
                    if (messageId == nil) {
                        messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
                    }
                    // 时间
                    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
                    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];//yyyy-MM-dd HH:mm:ss
                    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
        
                    NSString *promptText = None; //提示文本
                    {
                        if ([notice isEqualToString:@"delete_member"]) {
                            promptText = [msg stringByReplacingCharactersInRange:NSMakeRange(2, 0) withString:nickname];
                        }
                        else if ([notice isEqualToString:@"set_admin"])
                        {
                            promptText = [msg stringByReplacingCharactersInRange:NSMakeRange(2, 0) withString:nickname];
                        }
                        else if([notice isEqualToString:@"invite"])
                        {
                            
                            promptText = [msg stringByReplacingCharactersInRange:NSMakeRange(2, 0) withString:nickname];
                        }
                        else if([notice isEqualToString:@"quit_group"])
                        {
                            promptText = [msg stringByReplacingCharactersInRange:NSMakeRange(0, 0) withString:nickname];
                        }else if ([notice isEqualToString:@"delete_group"]){
                            promptText = [msg stringByReplacingCharactersInRange:NSMakeRange(2, 0) withString:nickname];

                        }
                    }
                    NSString *contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:group_id]];
                    //创建ChatMessage对象并保存到数据库表
                    MessageBase *wxmsg = [[MessageBase alloc] init];
                    wxmsg.messageId = messageId;
                    wxmsg.messageType = ChatMsgBody_Prompt;
                    wxmsg.messageBody = promptText; //[NSString stringWithFormat:@"%@ %@",nickname,msg];
                    
                    wxmsg.createTime = currentDateStr;
                    
                    wxmsg.messageStatus = Chat_Receive_Success;
                    wxmsg.contactId = [Utility getBareContactId:group_id];
                    wxmsg.contactName = contactName;
                    wxmsg.isIncoming = Msg_In;
                    wxmsg.isGroupMsg = YES;
                    
                    wxmsg.isRead = NO;
                    wxmsg.duration = 0;
                    wxmsg.content = None;
                    wxmsg.thumbnail = None;
                    
                    wxmsg.localFileUrl = None;
                    wxmsg.serverFileName = None;
                    wxmsg.fileSize = 0;
                    wxmsg.fileName = None;
                    
                    id messageObj = [self distributeMsgType:wxmsg.messageType message:wxmsg];

                    BOOL ret = [ChatMessageMgr saveChatMessageObj:wxmsg];
                    if (ret)
                    {
                        //发送收到确认Ack
                        [self sendReciveMsgAckfromJid:to to:from msgId:messageId isGroup:YES];
                    }
#pragma mark -踢出群成员
                    if ([notice isEqualToString:@"delete_member"]) {
                        [ChatGroupMgr deleteGroupListByGroupId:group_id]; //删除数据库中的群
                        
                        NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                   group_id,@"GroupId",
                                                   @"success",@"State",
                                                   @"0",@"ErrorCode",nil];
                        //删除群组结果通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupDeleteNotifaction object:notifiDic];
                    }
#pragma mark - 邀请好友 －－
                    else if([notice isEqualToString:@"invite"])
                    {
                        NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                   group_id,@"GroupId",
                                                   @"success",@"State",
                                                   @"被邀请加入群组",@"Description",nil];
                        //更新群组结果通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
                    }
#pragma mark - 退出某群组－－－
                    else if([notice isEqualToString:@"quit_group"])
                    {
//                        [ChatGroupMgr deleteGroupListByGroupId:group_id]; //删除数据库中的群

                    
                    }
#pragma mark - 解散群－－－
                    else if([notice isEqualToString:@"delete_group"])
                    {
                        NSString *groupName = [ChatGroupMgr fetchGroupNameInGroupBackUpByGroupId:group_id];
                        
                        [ChatGroupMgr deleteGroupListByGroupId:group_id]; //删除数据库中的群
                        [[IWxChatMgrGroup sharedGroup] deleteAllMessageToContactId:group_id];
#warning message -收到解散群的信息 --发出通知之类的
//                        [[NSNotificationCenter defaultCenter]postNotificationName:kXmppGroupDeleteOrQuitNotification
//                                                                           object:@{@"groupID":group_id,@"groupName":groupName}];
//                        
                        [[NSNotificationCenter defaultCenter]postNotificationName:kXmppRecentListUpdateNotification
                                                                           object:nil];

                        
                    }
#pragma mark - 移交管理员权限
                    else if ([notice isEqualToString:@"set_admin"])
                    {
                        ChatGroupMember *readObj = [ChatGroupMgr readGroupMemberByGroupId:group_id withMemberId:[Utility getBareContactId:self.logRegWxUserObject.UserId]];
                        NSMutableDictionary *chatGroupMemberDic = [[NSMutableDictionary alloc] init];
                        [chatGroupMemberDic setValue:group_id forKey:@"group_id"];
                        [chatGroupMemberDic setValue:@"owner" forKey:@"member_affiliations"];
                        [chatGroupMemberDic setValue:readObj.member_nickname forKey:@"member_nickname"];
                        [chatGroupMemberDic setValue:readObj.member_id forKey:@"member_id"];
                        [ChatGroupMgr saveChatGroupMemberDic:chatGroupMemberDic];
                        NSDictionary *notifiDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                   group_id,@"GroupId",
                                                   @"success",@"State",
                                                   @"被邀请加入群组",@"Description",nil];
                        //更新群组结果通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPGroupUpdateNotifaction object:notifiDic];
                    }

                    
                        
                    //消息委托
                    if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(didReceiveMessageType:messageObj:)])
                    {
                        [self.xmppMsgDelegate didReceiveMessageType:wxmsg.messageType messageObj:messageObj];
                    }
                }
            }
        }
        
        return;
    }
    
#pragma mark - groupchat  群聊－－
    if ([message.type isEqualToString:@"groupchat"]) //群聊天消息
    {
        return;
        if (messageId != nil)
        {
            NSUInteger messageType;
            
            //消息接收到的时间
            NSString *created_at = [[message attributeForName:@"created_at"] stringValue];
            if([created_at isEqualToString:@""]){
                created_at = [NSString stringFromDate:[NSDate date]];
            }
            NSString *sfileName   = None;
            NSUInteger duration   = 0;
            NSUInteger fileSize   = 0;
            
            NSString *messageBody = [[message elementForName:@"body"] stringValue];
            NSString *contentType = [[message elementForName:@"contentType"] stringValue];
            NSString *fileName = [[message elementForName:@"fileName"] stringValue];
            NSString *fileContentSize = [[message elementForName:@"fileSize"] stringValue];
            NSString *fileduration = [[message elementForName:@"duration"] stringValue];
            sfileName = messageBody;
            
            fileSize = [fileContentSize longLongValue];
            duration = [fileduration integerValue];
            
            if([contentType hasPrefix:@"image"]){
                //图片
                messageBody = @"图片";
                messageType = ChatMsgBody_Image;
                
            }else  if([contentType hasPrefix:@"audio"]){
                //语音
                messageBody = @"语音";
                messageType = ChatMsgBody_Voice;
                
                
            }else  if([contentType hasPrefix:@"video"]){
#warning message -文件的下载逻辑需要自己完善
                //视频
//                [DownFileManager downFileUrlStr:messageBody
//                                       fileType:kChatMsgBody_Video
//                                       fileName:fileName];
                messageBody = @"小视频";
                messageType = ChatMsgBody_Video;
                
                
            }else  if([contentType hasPrefix:@"*/*"]){
                //文件
                messageBody = @"文件";
                messageType = ChatMsgBody_File;
                
            }else{
                messageType = ChatMsgBody_Text;
                
            }
            
            
            NSString *contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:from]];
            
            //创建ChatMessage对象并保存到数据库表
            MessageBase *wxmsg = [[MessageBase alloc] init];
            wxmsg.messageId     = messageId;
            wxmsg.messageType   = messageType;
            wxmsg.messageBody   = messageBody;
            wxmsg.createTime    = created_at;
            wxmsg.messageStatus = Chat_Receive_Success;
            wxmsg.contactId     = [Utility getBareContactId:from];
            wxmsg.contactName   = contactName;
            wxmsg.isIncoming    = Msg_In;
            wxmsg.isGroupMsg    = YES;
            
            wxmsg.isRead         = NO;
            wxmsg.duration       = duration;
            wxmsg.thumbnail      = None;
            wxmsg.localFileUrl   = None;
            wxmsg.serverFileName = sfileName;
            wxmsg.fileSize       = fileSize;
            wxmsg.fileName       = fileName;
            NSArray *groupMemArray = [fromStr componentsSeparatedByString:@"/"];
            if (groupMemArray.count > 0) {
                wxmsg.frommemberID = [groupMemArray lastObject];
            }
            
            id messageObj = [self distributeMsgType:wxmsg.messageType message:wxmsg];
            
            BOOL ret = [ChatMessageMgr saveChatMessageObj:wxmsg];
            if (ret)
            {
                //发送收到确认Ack
                [self sendReciveMsgAckfromJid:to to:from msgId:messageId isGroup:YES];
            }
#warning message - 更新聊天列表页面
            [[NSNotificationCenter defaultCenter]postNotificationName:kXmppRecentListUpdateNotification
                                                               object:nil];
            //消息委托
            if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(didReceiveMessageType:messageObj:)])
            {
                //将消息是否已读状态置为 已读
   //             [WXMessageObject saveUpdateMessageId:messageId fieldName:@"messageIsRead" value:@"YES"];
                [self.xmppMsgDelegate didReceiveMessageType:messageType messageObj:messageObj];
            }
//            [self locationNotificationStr:[NSString stringWithFormat:@"群消息:%@",messageBody]];

        }

        
        WXLog(@"收到groupchat消息");
        return; //创建群聊，回应创建 请求配置表单
    }
    //服务器返回错误error
    else if ([message.type isEqualToString:@"error"])
    {
        NSXMLElement *error = [message elementForName:@"error"];
        NSString *errorCode = [error attributeStringValueForName:@"code"];
        [self willSendMessageCallbackState:Chat_Send_Success messageId:messageId error:errorCode];
    }
#pragma mark -  单人聊天消息
    else  //if ([message.type isEqualToString:@"chat"])
    {
        /**获取服务器消息记录*/
        NSXMLElement *tempresult = [message elementForName:@"result" xmlns:@"urn:xmpp:mam:1"];
        if (tempresult) {
            
            if ([kUserDefault boolForKey:@"IsFristFectch"]) {
                /**删除聊天记录*/
                [[IWxChatMgrGroup sharedGroup] deleteAllMessageToContactId:[kUserDefault objectForKey:@"ContactMemId"]];
                [kUserDefault setBool:NO forKey:@"IsFristFectch"];
                [kUserDefault synchronize];
            }

            
            NSXMLElement *tempforwarded = [tempresult elementForName:@"forwarded" xmlns:@"urn:xmpp:forward:0"];
            NSXMLElement *tempmessage = [tempforwarded elementForName:@"message" xmlns:@"jabber:client"];
        
            NSString *tempfromStr = [[tempmessage attributeForName:@"from"] stringValue];
            NSArray *tempfromArray = [tempfromStr componentsSeparatedByString:@"@"];
            NSString *tempfrom = tempfromArray[0];
            NSString *tempfromName = tempfrom;//通知栏显示的名称
                        
            __block NSString *tempmessageId = [[tempmessage attributeForName:@"id"] stringValue];
            
            /**如果messageid 为空 取archived 标签里面的*/
            if (tempmessageId== nil) {
                
                NSXMLElement *archived = [tempmessage elementForName:@"archived" xmlns:@"urn:xmpp:mam:tmp"];
                tempmessageId = [[archived attributeForName:@"id"] stringValue];
            }
            NSUInteger messageType;
            
            //消息接收到的时间
            NSXMLElement *tempdelay = [tempforwarded elementForName:@"delay" xmlns:@"urn:xmpp:delay"];

            NSString *created_at = [[tempdelay attributeForName:@"stamp"] stringValue];
            if([created_at isEqualToString:@""]){
                created_at = [NSString stringFromDate:[NSDate date]];
            }else{
                created_at = [NSString stringFromeTimeString:created_at];
            }
            
            NSString *sfileName   = None;
            NSUInteger duration   = 0;
            NSUInteger fileSize   = 0;
            
            NSString *messageBody = [[tempmessage elementForName:@"body"] stringValue];
            NSString *contentType = [[tempmessage elementForName:@"contentType"] stringValue];
            NSString *fileName = [[tempmessage elementForName:@"fileName"] stringValue];
            NSString *fileContentSize = [[tempmessage elementForName:@"fileSize"] stringValue];
            NSString *fileduration = [[tempmessage elementForName:@"duration"] stringValue];
            sfileName = messageBody;
            
            fileSize = [fileContentSize longLongValue];
            duration = [fileduration integerValue];
            
            if([contentType hasPrefix:@"image"]){
                //图片
                messageBody = @"图片";
                messageType = ChatMsgBody_Image;
                
            }else  if([contentType hasPrefix:@"audio"]){
                //语音
                messageBody = @"语音";
                messageType = ChatMsgBody_Voice;
                
                
            }else  if([contentType hasPrefix:@"video"]){
                //视频
                messageBody = @"小视频";
                messageType = ChatMsgBody_Video;
                
                
            }else  if([contentType hasPrefix:@"*/*"]){
                //文件
                messageBody = @"文件";
                messageType = ChatMsgBody_File;
                
            }else if ([contentType hasPrefix:@"money"]){
                messageType = ChatMsgBody_File;
                return;
            }else {
                messageType = ChatMsgBody_Text;
                /**h5文本消息 有些自己家的div 去除*/
                if ([messageBody containsString:@"&lt;div"]) {
                    messageBody = [[messageBody componentsSeparatedByString:@"&lt;div"] firstObject];
                }
                /**微信发的 是按文本消息 URL拼接?id=*/
                if (([messageBody containsString:@".jpg?id="]||[messageBody containsString:@".jpeg?id="]||[messageBody containsString:@".gif?id="]||[messageBody containsString:@".png?id="])&& [messageBody hasPrefix:@"http://tianjiu.oss"]) {
                    messageBody = @"图片";
                    messageType = ChatMsgBody_Image;
                    sfileName = [[sfileName componentsSeparatedByString:@"?id="]firstObject];
                }
                /**安卓发的图片 是按文本消息 URL拼接?id=*/
                if (([messageBody containsString:@".jpg"]||[messageBody containsString:@".jpeg"]||[messageBody containsString:@".gif"]||[messageBody containsString:@".png"])&& [messageBody hasPrefix:@"http://tianjiu.oss"]&&![messageBody containsString:@"?id="]) {
                    messageBody = @"图片";
                    messageType = ChatMsgBody_Image;
                }

            }
            
            
            NSString *contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:tempfrom]];
            
            //创建ChatMessage对象并保存到数据库表
            MessageBase *wxmsg = [[MessageBase alloc] init];
            wxmsg.messageId     = tempmessageId;
            wxmsg.messageType   = messageType;
            wxmsg.messageBody   = messageBody;
            wxmsg.createTime    = created_at;
            wxmsg.messageStatus = Chat_Receive_Success;
            wxmsg.contactName   = contactName;
            wxmsg.isGroupMsg    = NO;
            
            wxmsg.isRead         = YES;
            wxmsg.duration       = duration;
            wxmsg.thumbnail      = None;
            wxmsg.localFileUrl   = None;
            wxmsg.serverFileName = sfileName;
            wxmsg.fileSize       = fileSize;
            wxmsg.fileName       = fileName?:sfileName;
            wxmsg.frommemberID   = tempfromName;
            if ([tempfrom isEqualToString:kUserLoginName]) {
                wxmsg.isIncoming = Msg_Out;
            }else{
                wxmsg.isIncoming    = Msg_In;
            }
            wxmsg.contactId = [kUserDefault objectForKey:@"ContactMemId"];
            
            [ChatMessageMgr saveChatMessageObjOnly:wxmsg];
            
            //发出更新聊天记录的通知
//            [[NSNotificationCenter defaultCenter]postNotificationName:kXmppRecentListUpdateNotification object:nil];

            return;
        }
        
        NSUInteger messageType;
        
        //消息接收到的时间
        NSString *created_at = [[message attributeForName:@"created_at"] stringValue]?:@"";
        if([created_at isEqualToString:@""]){
            created_at = [NSString stringFromDate:[NSDate date]];
        }
        NSString *sfileName   = None;
        NSUInteger duration   = 0;
        NSUInteger fileSize   = 0;
        
        NSString *messageBody = [[message elementForName:@"body"] stringValue];
        NSString *contentType = [[message elementForName:@"contentType"] stringValue];
        NSString *fileName = [[message elementForName:@"fileName"] stringValue];
        NSString *fileContentSize = [[message elementForName:@"fileSize"] stringValue];
        NSString *fileduration = [[message elementForName:@"duration"] stringValue];
        sfileName = messageBody;
        
        fileSize = [fileContentSize longLongValue];
        duration = [fileduration integerValue];
        
        if([contentType hasPrefix:@"image"]){
            //图片
            messageBody = @"图片";
            messageType = ChatMsgBody_Image;
            
        }else  if([contentType hasPrefix:@"audio"]){
            //语音
            messageBody = @"语音";
            messageType = ChatMsgBody_Voice;
            
            
        }else  if([contentType hasPrefix:@"video"]){
            //视频
//            [self downFileUrlStr:messageBody fileType:kChatMsgBody_Video fileName:fileName];
//            [DownFileManager downFileUrlStr:messageBody fileType:kChatMsgBody_Video fileName:fileName];

            messageBody = @"小视频";
            messageType = ChatMsgBody_Video;

            
        }else  if([contentType hasPrefix:@"*/*"]){
            //文件
            messageBody = @"文件";
            messageType = ChatMsgBody_File;
            
        }else if ([contentType hasPrefix:@"money"]){
            messageType = ChatMsgBody_File;
            return;
        }else{
            messageType = ChatMsgBody_Text;
            /**h5文本消息 有些自己家的div 去除*/
            if ([messageBody containsString:@"&lt;div"]) {
                messageBody = [[messageBody componentsSeparatedByString:@"&lt;div"] firstObject];
            }
            /**微信发的 是按文本消息 URL拼接?id=*/
            if (([messageBody containsString:@".jpg?id="]||[messageBody containsString:@".jpeg?id="]||[messageBody containsString:@".gif?id="]||[messageBody containsString:@".png?id="])&& [messageBody hasPrefix:@"http://tianjiu.oss"]) {
                messageBody = @"图片";
                messageType = ChatMsgBody_Image;
                sfileName = [[sfileName componentsSeparatedByString:@"?id="]firstObject];
            }
            /**安卓发的图片 是按文本消息 URL拼接?id=*/
            if (([messageBody containsString:@".jpg"]||[messageBody containsString:@".jpeg"]||[messageBody containsString:@".gif"]||[messageBody containsString:@".png"])&& [messageBody hasPrefix:@"http://tianjiu.oss"]&&![messageBody containsString:@"?id="]) {
                messageBody = @"图片";
                messageType = ChatMsgBody_Image;
            }
            
        }
        
        
        NSString *contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:from]];
        
        //创建ChatMessage对象并保存到数据库表
        MessageBase *wxmsg = [[MessageBase alloc] init];
        wxmsg.messageId     = messageId;
        wxmsg.messageType   = messageType;
        wxmsg.messageBody   = messageBody;
        wxmsg.createTime    = created_at;
        wxmsg.messageStatus = Chat_Receive_Success;
        wxmsg.contactId     = [Utility getBareContactId:from];
        wxmsg.contactName   = contactName;
        wxmsg.isIncoming    = Msg_In;
        wxmsg.isGroupMsg    = NO;
        
        wxmsg.isRead         = NO;
        wxmsg.duration       = duration;
        wxmsg.thumbnail      = None;
        wxmsg.localFileUrl   = None;
        wxmsg.serverFileName = sfileName;
        wxmsg.fileSize       = fileSize;
        wxmsg.fileName       = fileName;
        wxmsg.frommemberID   = fromName;

        id messageObj = [self distributeMsgType:wxmsg.messageType message:wxmsg];
        BOOL ret = [ChatMessageMgr saveChatMessageObj:wxmsg];
        if (ret)
        {
            //发送收到确认Ack
            [self sendReciveMsgAckfromJid:to to:from msgId:messageId isGroup:NO];
        }
#warning message - 发出更新聊天记录的通知
        [[NSNotificationCenter defaultCenter]postNotificationName:kXmppRecentListUpdateNotification
                                                           object:nil];
        //消息委托
        if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(didReceiveMessageType:messageObj:)])
        {
            [self.xmppMsgDelegate didReceiveMessageType:wxmsg.messageType messageObj:messageObj];
        }
        NSDictionary *params = @{@"fromUserId":wxmsg.contactId,@"toUserId":kUserId};

        [self locationNotificationStr:[NSString stringWithFormat:\
                                       @"您有一条新消息"] parm:params];
    }
    

    return;
}

#pragma mark - 本地通知相关－－
/**
 *  本地推送在线消息
 *
 *  @param messageBody 通知栏看到的消息体
 */
- (void)locationNotificationStr:(NSString *)messageBody parm:(NSDictionary *)dic
{
    //程序运行在前台，消息正常显示  Vincefu
    if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || [[UIApplication sharedApplication] applicationState] == UIApplicationStateInactive)
    {
        
    }
    else
    {
//        [NetWork PostNetWorkWithUrl:kAppIsPushMessage with:dic successBlock:^(NSDictionary *dic) {
//            NSDictionary *temp = dic[@"dataobj"];
//            BOOL ispush = [temp[@"push"] boolValue];
//            if (ispush) {
//                UIUserNotificationType types = UIUserNotificationTypeAlert;
//                UIUserNotificationSettings *mySettings =[UIUserNotificationSettings settingsForTypes:types categories:nil];
//                [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
//
//                //如果程序在后台运行，收到消息以通知类型来显示
//                UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//                localNotification.alertAction = @"Ok";
//                localNotification.alertBody = messageBody;//通知主体
//                localNotification.soundName = UILocalNotificationDefaultSoundName;//通知声音
//                localNotification.applicationIconBadgeNumber++;//标记数
//                [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];//发送通知
//            }
//        } FailureBlock:^(NSString *msg) {
//
//        } errorBlock:^(id error) {
//
//        }];
    }
}

//保存聊天文件
-(BOOL)saveChatFileName:(NSString *)fileName withData:(NSData *)data
{
    if (fileName==nil || [fileName isEqualToString:@""] || data == nil) {
        return NO;
    }
    NSString *localFilePathName = [NSString wbChatPathWithType:kChatMsgBody_Image];
    [NSString checkFileFolderPathExist:localFilePathName];
    
    localFilePathName = [NSString stringWithFormat:@"%@/%@",localFilePathName,fileName];
    BOOL ret = [data writeToFile:localFilePathName atomically:YES];
    return ret;
}
//将即将发送到IM服务器的文件保存到im目录下之后删除
- (void)deleteDocomentsChatFileName:(NSString *)fileName
{
    NSString *localFilePathName = [NSString stringWithFormat:@"%@/%@",DATABASE_PATH,fileName];
    NSFileManager *fileManager =  [NSFileManager defaultManager];
    [fileManager removeItemAtPath:localFilePathName error:nil];
}

//#define ChatMsgBody_Text         1
//#define ChatMsgBody_Image        2
//#define ChatMsgBody_Video        3
//#define ChatMsgBody_Voice        4
//#define ChatMsgBody_SelfDefine, 大于100为自定义消息类型
//
//ChatMsgBody_Prompt = 0,       //提示消息 只会收到
//分发转换成对应消息类型
- (id)distributeMsgType:(NSUInteger)msgType message:(MessageBase *)wxmsg
{
    id messageObj = nil;
    switch (wxmsg.messageType)
    {
        case ChatMsgBody_Text:
        case ChatMsgBody_Prompt:
        {
            ChatTextMessage *ctMObj = [[ChatTextMessage alloc] init];
            ctMObj.messageId = wxmsg.messageId;
            ctMObj.messageType = wxmsg.messageType;
            ctMObj.textMessage = wxmsg.messageBody;
            ctMObj.createTime = wxmsg.createTime;
            
            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId = wxmsg.contactId;
            ctMObj.isIncoming = wxmsg.isIncoming;
            ctMObj.isGroupMsg = wxmsg.isGroupMsg;
            ctMObj.fromMemberID = wxmsg.frommemberID;
            
            ctMObj.isRead = wxmsg.isRead;
            
            messageObj = ctMObj;
        }
            break;
        case ChatMsgBody_Image:
        {
            ChatPhotoMessage *ctMObj = [[ChatPhotoMessage alloc] init];
            ctMObj.messageId     = wxmsg.messageId;
            ctMObj.messageType   = wxmsg.messageType;
            ctMObj.thumbnail     = wxmsg.thumbnail;
            ctMObj.createTime    = wxmsg.createTime;

            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId     = wxmsg.contactId;
            ctMObj.isIncoming    = wxmsg.isIncoming;
            ctMObj.isGroupMsg    = wxmsg.isGroupMsg;

            ctMObj.isRead        = wxmsg.isRead;
            ctMObj.fromMemberID = wxmsg.frommemberID;
            
            ctMObj.localFileUrl = wxmsg.serverFileName;

            ctMObj.fileSize = wxmsg.fileSize;
            ctMObj.fileName = wxmsg.fileName;
            
            messageObj = ctMObj;
        }
            break;
        case ChatMsgBody_Video:
        {
            ChatVideoMessage *ctMObj = [[ChatVideoMessage alloc] init];
            ctMObj.messageId = wxmsg.messageId;
            ctMObj.messageType = wxmsg.messageType;
            ctMObj.thumbnail = wxmsg.thumbnail;
            ctMObj.createTime = wxmsg.createTime;
            
            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId = wxmsg.contactId;
            ctMObj.isIncoming = wxmsg.isIncoming;
            ctMObj.isGroupMsg = wxmsg.isGroupMsg;
            ctMObj.fromMemberID = wxmsg.frommemberID;

            ctMObj.isRead = wxmsg.isRead;
            
            if (ctMObj.isIncoming) {
                ctMObj.localFileUrl = wxmsg.serverFileName;
            }
            else
            {
                ctMObj.localFileUrl = wxmsg.localFileUrl;
            }
            ctMObj.fileSize = wxmsg.fileSize;
            ctMObj.fileName = wxmsg.fileName;
            ctMObj.duration = wxmsg.duration;
            
            messageObj = ctMObj;
        }
            break;
        case ChatMsgBody_Voice:
        {
            ChatAudioMessage *ctMObj = [[ChatAudioMessage alloc] init];
            ctMObj.messageId     = wxmsg.messageId;
            ctMObj.messageType   = wxmsg.messageType;
            ctMObj.createTime    = wxmsg.createTime;

            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId     = wxmsg.contactId;
            ctMObj.isIncoming    = wxmsg.isIncoming;
            ctMObj.isGroupMsg    = wxmsg.isGroupMsg;
            ctMObj.fromMemberID = wxmsg.frommemberID;

            ctMObj.isRead        = wxmsg.isRead;
            
            if (ctMObj.isIncoming) {
                ctMObj.localFileUrl = wxmsg.serverFileName;
                ctMObj.fileName = wxmsg.serverFileName;

            }
            else
            {
                ctMObj.fileName = wxmsg.fileName;

            }
            ctMObj.fileSize = wxmsg.fileSize;
            ctMObj.duration = wxmsg.duration;
            
            messageObj = ctMObj;
        }
            break;
        case ChatMsgBody_File:
        {
            ChatFileMessage *ctMObj = [[ChatFileMessage alloc] init];
            ctMObj.messageId     = wxmsg.messageId;
            ctMObj.messageType   = wxmsg.messageType;
            ctMObj.createTime    = wxmsg.createTime;
            
            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId     = wxmsg.contactId;
            ctMObj.isIncoming    = wxmsg.isIncoming;
            ctMObj.isGroupMsg    = wxmsg.isGroupMsg;
            ctMObj.fromMemberID = wxmsg.frommemberID;
            
            ctMObj.isRead        = wxmsg.isRead;
            
            if (ctMObj.isIncoming) {
                ctMObj.localFileUrl = wxmsg.serverFileName;
                ctMObj.fileName = wxmsg.fileName;
                
            }
            else
            {
                ctMObj.fileName = wxmsg.fileName;
                
            }
            ctMObj.fileSize = wxmsg.fileSize;
            
            messageObj = ctMObj;
        }
            break;
            
        default:
        {
            ChatCustomMessage *ctMObj = [[ChatCustomMessage alloc] init];
            ctMObj.messageId = wxmsg.messageId;
            ctMObj.messageType = wxmsg.messageType;
            ctMObj.content = wxmsg.messageBody;
            ctMObj.createTime = wxmsg.createTime;
            
            ctMObj.messageStatus = wxmsg.messageStatus;
            ctMObj.contactId = wxmsg.contactId;
            ctMObj.isIncoming = wxmsg.isIncoming;
            ctMObj.isGroupMsg = wxmsg.isGroupMsg;
            ctMObj.fromMemberID = wxmsg.frommemberID;

            ctMObj.isRead = wxmsg.isRead;
            
            messageObj = ctMObj;
        }
            break;
    }
    return messageObj;
}

#pragma mark --didReceivePresence--
//好友上下线通知  //实时获取好友的状态
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    //拨打电话控制流程 判断iq.type串中是否包含ucfCallMgr_这个串，
    if ([presence.type isEqualToString:@"oncall"]
        ||[presence.type isEqualToString:@"member"]
        ||[presence.type isEqualToString:@"online"]
        ||[presence.type isEqualToString:@"offline"])
    {
        [[ucfCallMgr sharedInstance] xmppStream:sender didReceivePresence:presence];
        return;
    }
    
//    NSLog(@"didReceivePresence : %@", [presence fromStr]);
    NSLog(@"didReceivePresence: presence: %@",presence);
    
    NSString *from = [presence fromStr];
    
    //当前用户
    NSString *myuserId = [[sender myJID] user];
    
    //取得好友状态 subscribed 通过验证好友添加请求 unsubscribed 对方拒绝
    NSString *presenceType = [presence type]; //available 上线/unavailable 下线
    
    //在线用户 不带域名和资源
    NSString *presenceFromUser = [[presence from] user];
    
    //收到 上线消息确认
    NSString *self_id = [NSString stringWithFormat:@"ucfgroupGoOnline_%@",logRegWxUserObject.UserName];
    if ([presence.elementID isEqualToString:self_id])
    {
        [xmppRoster fetchRoster]; //获取联系人
        return;
    }
    
    NSString *fromUserJid = [[presence from] bare];
    if ([presence.type isEqualToString: @"groupchat"])
    {
        //判断message类型，是否包含chat.wx.com
        NSRange range = [fromUserJid rangeOfString:@"chat.wx.com"];
        if (range.length >0)//包含
        {
            NSString *subject = [[presence elementForName:@"subject"] stringValue];
            if (subject!= nil)
            {
//                ChatGroup *savedata = [[ChatGroup alloc] init];
//                savedata.roomjid = fromUserJid;
//                savedata.nickname = subject;
//                savedata.self_nick = logRegWxUserObject.userNickname;
//                [ChatGroupMgr saveGroupUser:savedata TableType:GroupUser];
            }
            return;
        }
    }
    
	/*
	 //如果不是自己，如果涉及多段登录，此处最好加上else，如果是自己离线的话，调用上线协议
	 XMPPPresence *presence = [XMPPPresence presence];
	 [[self xmppStream] sendElement:presence];
	 */
    if (![presenceFromUser isEqualToString:myuserId]) //如果不想让自己出现在列表中
	{
        //用户在线通知
        if ([presenceType isEqualToString:@"available"])//用户在线或上线通知
		{
			//列表和数据库都要相应改变
            //用户列表委托
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(didChangedOnlineStatus:forContactId:)])
            {
                [xmppContactDelegate didChangedOnlineStatus:YES forContactId:presenceFromUser];
            }
            //发送收到联系人更新通知
            [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPBuddyOnlineOfflineNotifaction object:presenceFromUser];
        }
        else if ([presenceType isEqualToString:@"unavailable"])//用户不在线或下线通知
		{
			//列表和数据库都要相应改变
            //用户列表委托
            if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(didChangedOnlineStatus:forContactId:)])
            {
                [xmppContactDelegate didChangedOnlineStatus:NO forContactId:presenceFromUser];
            }
        }
        else if ([presenceType isEqualToString:@"subscribed"])
        {
//            //这里再次处理添加好友
//            XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@",[presence from]]];
//            [xmppRoster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
        }
        else if ([presenceType isEqualToString:@"subscribe"])
        {
            //   ChatContactRequest
            NSString *inviteMessage = [[presence elementForName:@"status"] stringValue];
            NSString *nickname = [[presence elementForName:@"status"] attributeStringValueForName:@"nickname"];
        
            NSMutableDictionary *contactObjDic = [[NSMutableDictionary alloc] init];
            [contactObjDic setObject:[Utility getBareContactId:from] forKey:@"ContactId"];
        
            if (nickname)
            {
                [contactObjDic setObject:presenceFromUser forKey:@"ContactName"];
            }
            else
            {
                [contactObjDic setObject:presenceFromUser forKey:@"ContactName"];
            }
        
            //当双方互相加好友，不在新朋友列表中，进行接受拒绝的操作时，主动发出好友请求后，对方又添加自己为好友，收到iq后，还会在收到好友请求消息。
            ChatContact *getContact = [ChatContactMgr fetchChatContactByContactId:[Utility getBareContactId:from]];
            if (getContact != nil) {
                return;
            }
            else
            {
                [contactObjDic setObject:NotDoing forKey:@"ContactState"];
            }
            
            [contactObjDic setObject:[NSNumber numberWithBool:NO] forKey:@"ContactIsSend"];
            
            if (inviteMessage) {
                [contactObjDic setObject:inviteMessage forKey:@"ContactText"];
            }
            
            BOOL ret =[ChatContactMgr saveChatContactRequestDic:contactObjDic];
            if (ret)
            {
                //发送收到新好友邀请通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kReceiveBuddyInviteMsg object:nil];
                
                if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(didReceiveContactsInviteMessage:message:)])
                {
                    [xmppContactDelegate didReceiveContactsInviteMessage:from message:inviteMessage];
                }
            }
        }
    }
}
#pragma mark -UIAlertViewDelegate－－－
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 900) {
        // 回到登录页面
        [[UserAccountManager shareUserAccountManager] logout];
    }
}
#warning message -－关于掉线的处理！！！！！！－－—－－—－－－－
// 连接，发送信息出错
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
	WXLog(@"didReceiveError error= %@",error);
    NSXMLElement *conflict = [error elementForName:@"conflict" xmlns:@"urn:ietf:params:xml:ns:xmpp-streams"];
    WXLog(@"%@",[conflict stringValue]);
    NSXMLElement *text = [error elementForName:@"text" xmlns:@"urn:ietf:params:xml:ns:xmpp-streams"];
    NSString *value = text.stringValue;
#pragma mark -收到这个操作是发出退出登录的操作 ，如果客户在前端就给出退出的alter提示
    if ([value isEqualToString:@"Replaced by new connection"])
    {
        
        isLoginSuccess = NO;
//        退出im 和 anyChat
        [[IWxChatMgrLogin sharedInstance]loginoff];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                            message:@"您的账号在其他设备登录！"
                                                           delegate:self
                                                  cancelButtonTitle:@"重新连接"
                                                  otherButtonTitles: nil];
        alertView.tag = 900;
        [alertView show];
        
    }
}

// 取消连接
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
	WXLog(@"xmppStreamDidDisconnect isXmppConnected= %d error = %@",isXmppConnected,error);
    [Utility writeToFileWithString:[NSString stringWithFormat:@"xmppStreamDidDisconnect isXmppConnected= %d isReConnecting= %d",isXmppConnected,isReConnecting] withFileIsDelete:NO];
   
    if (!isReConnecting)
    {
        //NSString *domain = error.domain;
        NSDictionary *userInfo = error.userInfo;
        NSString *decrp = [userInfo objectForKey:@"NSLocalizedDescription"];
        
        isXmppConnected = [xmppStream isConnected];
        
        if (!isXmppConnected)
        {
            if (loginOrRegState == connectserver_Error) {
                WXLog(@"xmppStreamDidDisconnect loginOrRegState == connectserver_Error");
                return;
            }
            
            WXLog(@"Unable to connect to server. Check xmppStream.hostName");
    
            //登录失败已经抛出失败状态，服务器主动断开连接，无需再次抛出状态
            if (loginOrRegState == login_Fail) {
                WXLog(@"xmppStreamDidDisconnect loginOrRegState == login_Fail");
                return;
            }
            
            if (self.isReg == YES) {
                self.isReg = NO;
                return;
            }
            
            
            if ([self.apiEntranceType isEqualToString:@"loginoff"]) {
                [self deleteXmppRecordReqId:@"loginoff"];
                if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginoffRspState:reason:)])
                {
                    [xmppLogRegDelegate loginoffRspState:NO reason:@"已断开连接！"];
                }
                self.apiEntranceType = nil;
                return;
            }
            
            [xmppStream disconnect];/////////////测试测试测试///////////
            
            isReConnecting = YES;
            //fuweivince
            if (reConnectTimer == nil) {
                reConnectTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconning object:nil];

            }
            else
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconning object:nil];
            }
        }
    }
    
    
        
#if 0  //主动disconnect或服务器断掉会触发
        NSDictionary *loginInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                   logRegWxUserObject.UserId, @"userid", logRegWxUserObject.UserPassword, @"password",
                                   @"不能连接上服务器，请检查网络或重试！", @"describe",nil];
  
        //用户登录--连接服务器失败
        if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
        {
            [xmppLogRegDelegate loginWithUserIdRspState:login_ConnectFail loginInfo:loginInfo];
        }
        
        if (self.completion) {
            self.completion(loginInfo, connectserver_Error);
        }
#endif
	
}

//调用函数 fuweivince
-(void)timerFireMethod:(NSTimer *)timer
{
    BOOL islogin = [self isLogSuccess];
    isXmppConnected = [xmppStream isConnected];
//    WXLog(@"timerFireMethod isXmppConnected= %d islogin= %d", isXmppConnected,islogin);
    //重新连接
    if (!isXmppConnected) {
        if (islogin) {
            [self connect];
        }
    }
//    else   999999999999999
//    {
//        [reConnectTimer invalidate];
//        reConnectTimer = nil;
//        isReConnecting = NO;
//        if (isXmppConnected == YES) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconnSucc object:nil];
//        }
//    }
}

- (void)becomeActive:(id)notification
{
    BOOL islogin = [self isLogSuccess];
    BOOL isConFlag = [xmppStream isConnected];
    WXLog(@"becameActive islogin= %d isConFlag= %d",islogin,isConFlag);
    
    if (islogin && isConFlag)
    {
        [self reloginpresence];

        [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconnSucc object:nil];
        isReConnecting = NO;
        return ;
    }
    else if (islogin && !isConFlag)
    {
        isReConnecting = YES;
        //fuweivince
        if (reConnectTimer == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPNetwrokErrorReconning object:nil];

            reConnectTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        }
    }
    else
    {
        WXLog(@"becameActive Not Login");
    }
}

//fusuwei
- (void)resignActive:(id)notification
{
    self.timerIdList = nil;
    
    [self goOffline];
    
    //获取得到所有未读消息列表
    NSMutableArray *unReadlist = [ChatMessageMgr getAllUnReadMessageList];
    NSInteger countNum = unReadlist.count;
    WXLog(@"resignActive countNum= %ld",(long)countNum);
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = countNum;//标记数
}

- (void)reloginpresence
{
    [self ucfgroupGoOnline];
    return;
    
    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:auth"];
    
    NSXMLElement *username = [NSXMLElement elementWithName:@"username"];
    [username setStringValue:self.logRegWxUserObject.UserId];
    [query addChild:username];
    
    NSXMLElement *password_d = [NSXMLElement elementWithName:@"password"];
    [password_d setStringValue:self.logRegWxUserObject.UserPassword];
    [query addChild:password_d];
    
    NSXMLElement *resource = [NSXMLElement elementWithName:@"resource"];
    [resource setStringValue:[[UcfgroupXMPPManger sharedInstance] generateXMPPresource]];
    [query addChild:resource];
    

    
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    
    [iq addAttributeWithName:@"type" stringValue:@"set"];
    [iq addAttributeWithName:@"id" stringValue:@"Login_ID"];
    [iq addChild:query];
    [xmppStream sendElement:iq];
}

#pragma mark XMPPRosterDelegate
//// 收到花名册
//- (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence
//{
//    WXLog(@"didReceiveBuddyRequest presence= %@", presence);
//}

////添加好友
//- (void)addSomeBody:(NSString *)userId
//{
//    [xmppRoster subscribePresenceToUser:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@hcios.com",userId]]];
//}

//将要发出消息CallBack
- (void)willSendMessageCallbackState:(ChatMsgState)state messageId:(NSString *)messageId error:(NSString *)error
{
    //将要发送消息
    if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)])
    {
        [ChatMessageMgr saveUpdateMessageId:messageId fieldName:@"messageStatus" valueInt:Chat_Send_Sending];
        [self.xmppMsgDelegate sendMessageRspState:state messageId:messageId error:error];
    }
}



/***********************************创建群************************
//创建群
/**
 *
 *  @param group_name 群组名称
 *  @param desc       群描述信息
 *  @param max
 *  @param yesorno    是否是公开群　０不公开，１公开
 *  @param isapproval 是否需要审批加入 此属性只针对公开群组有效
 */
- (void)ucfgroup_CreateGroupName:(NSString *)group_name
                            desc:(NSString *)desc
                       memberMax:(NSInteger)max
                        isPublic:(BOOL)yesorno
                      isApproval:(BOOL)isapproval
{
    NSString *createGroupiqID = [NSString stringWithFormat:@"%@%@",@"ucfgroup_CreateGroupName.",\
                                 [NSString stringWithFormat:@"%d",[self getRandomNumber:1000000 to:9000000]]];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"type" stringValue:@"set"];
    [iq addAttributeWithName:@"to" stringValue:kXMPPGroupDomain];
    [iq addAttributeWithName:@"id" stringValue:createGroupiqID];
    
    NSXMLElement *create = [NSXMLElement elementWithName:@"create"];
    [create addAttributeWithName:@"group_name" stringValue:group_name];
    [create addAttributeWithName:@"desc" stringValue:desc];
    [create addAttributeWithName:@"public" stringValue:[NSString stringWithFormat:@"%d",yesorno]];
    [create addAttributeWithName:@"approval" stringValue:[NSString stringWithFormat:@"%d",isapproval]];
    [create addAttributeWithName:@"max" stringValue:[NSString stringWithFormat:@"%ld",(long)max]];
    
    NSXMLElement *group = [NSXMLElement elementWithName:@"group" xmlns:@"http://www.ucfgroup.com/protocol/group"];
    [group addChild:create];
    
    [iq addChild:group];
    
    [xmppStream sendElement:iq];
    
    {
        NSMutableDictionary *chatGroupDic = [[NSMutableDictionary alloc] init];
        [chatGroupDic setValue:createGroupiqID forKey:@"group_id"];
        [chatGroupDic setValue:group_name forKey:@"group_name"];
        [chatGroupDic setValue:[NSString stringWithFormat:@"%d",yesorno] forKey:@"group_public"];
        [chatGroupDic setValue:[NSString stringWithFormat:@"%d",isapproval] forKey:@"group_approval"];
        [chatGroupDic setValue:desc forKey:@"group_desc"];
        [chatGroupDic setValue:[self getCurrentTime] forKey:@"group_createTime"];
        [chatGroupDic setValue:[NSString stringWithFormat:@"%ld",(long)max] forKey:@"group_membersMax"];
        
        [ChatGroupMgr saveChatGroupDic:chatGroupDic];
        [ChatGroupMgr saveChatGroupBackUpDic:chatGroupDic];

        
        [self addXmppRecordReqId:createGroupiqID type:@"creatGroupName" paraMsg:chatGroupDic];
    }
}

//判断当前登录用户是否登录成功
- (BOOL)isLogSuccess
{
    if(isLoginSuccess)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark-------处理查询是否返回超时------
//添加回应超时处理      reqTimer和reqId和paraMsg数组
- (void)addXmppRecordReqId:(NSString*)reqId type:(NSString*)type paraMsg:(id)paraMsg
{
    if (paraMsg == nil) {
        paraMsg = @"";
    }
    WXLog(@"addXmppRecordReqId reqId= %@",reqId);
    
    NSArray *tempArray = [NSArray arrayWithArray:self.timerIdList];
    for (NSDictionary *tempDic in tempArray) {
        NSString *tempType = tempDic[@"reqType"];
        if ([tempType isEqualToString:type]) {
            [self.timerIdList removeObject:tempDic];
        }
    }
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(addXmppRecordTimerFired:) userInfo:nil repeats:NO];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                reqId,@"reqId",timer,@"reqTimer",
                                paraMsg,@"paraMsg",type,@"reqType",
                                nil];
    [self.timerIdList addObject:dic];
}

//addXmppRecordtimer调用函数
-(void)addXmppRecordTimerFired:(NSTimer *)timer
{
    NSInteger count = [self.timerIdList count];
    NSMutableDictionary *dic = nil;
    for (int i=0; i<count; i++) {
        dic = [self.timerIdList objectAtIndex:i];
        if ([timer isEqual:[dic objectForKey:@"reqTimer"]]) {
            break;
        }
    }
    
    [self handleReqRspByDic:dic];
}
//删除回应超时处理
-(void)deleteXmppRecordReqId:(NSString*)reqId
{
    NSInteger count = [self.timerIdList count];
    WXLog(@"RecordReqArray count = %ld",(long)count);
    NSMutableDictionary *dic = nil;
    NSTimer *curTimer = nil;
    
    
    for (int i=0; i<count; i++) {
        dic = [self.timerIdList objectAtIndex:i];
        if ([reqId isEqualToString:[dic objectForKey:@"reqId"]]) {
            curTimer = [dic objectForKey:@"reqTimer"];
            [curTimer invalidate];
            curTimer = nil;
            WXLog(@"deleteXmppRecordReqId reqId= %@",[dic objectForKey:@"reqId"]);
            [self.timerIdList removeObject:dic];
            break;
        }
    }
}

-(void)handleReqRspByDic:(NSMutableDictionary*)dic
{
    id paraMsg = [dic objectForKey:@"paraMsg"];
    NSTimer *reqTimer = [dic objectForKey:@"reqTimer"];
    NSString *reqType = [dic objectForKey:@"reqType"];
    
    WXLog(@"处理超时 reqId= %@",[dic objectForKey:@"reqId"]);
    
    NSString *msgId = [dic objectForKey:@"reqId"];
    
    //消息
    if ([reqType isEqualToString:@"sendMessageRspState:messageId:error:"])
    {
        if ((self.xmppMsgDelegate != nil) && [self.xmppMsgDelegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)])
        {
            [ChatMessageMgr saveUpdateMessageId:paraMsg fieldName:@"messageStatus" valueInt:Chat_Send_Failure];
            [self.xmppMsgDelegate sendMessageRspState:Chat_Send_Failure messageId:paraMsg error:@"超时"];
        }
        
        return;
    }
    //注册登录
    if ([reqType isEqualToString:@"registerNewAccount"])
    {
        if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(registerNewAccountRspState:username:password:)])
        {
            [xmppLogRegDelegate registerNewAccountRspState:connectTimeout_Error username:logRegWxUserObject.UserId password:logRegWxUserObject.UserPassword];
        }
        return;
    }
    if ([reqType isEqualToString:@"loginWithUserId"])
    {
        WXLog(@"此用户已经通过验证，登陆超时！！！！！");
        if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginWithUserIdRspState:loginInfo:)])
        {
            [xmppLogRegDelegate loginWithUserIdRspState:connectTimeout_Error loginInfo:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"loginoff"])
    {
        if (xmppLogRegDelegate && [xmppLogRegDelegate respondsToSelector:@selector(loginoffRspState:reason:)])
        {
            [xmppLogRegDelegate loginoffRspState:NO reason:@"超时"];
        }
        return;
    }
    //联系人
    if ([reqType isEqualToString:@"requestMyAllContacts"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(requestMyAllContactsRspState:errorState:)])
        {
            [xmppContactDelegate requestMyAllContactsRspState:Contact_Failure errorState:Contact_Timerout_Error];
        }
        return;
    }
    if ([reqType isEqualToString:@"inviteContact"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(inviteContactRspState:contactId:errorState:)])
        {
            [xmppContactDelegate inviteContactRspState:Contact_Failure contactId:nil errorState:Contact_Timerout_Error];
        }
        return;
    }
    if ([reqType isEqualToString:@"rejectInviteContact"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(rejectInviteContactRspState:contactId:errorState:)])
        {
            [xmppContactDelegate rejectInviteContactRspState:Contact_Failure contactId:nil errorState:Contact_Timerout_Error];
        }
        return;
    }
    if ([reqType isEqualToString:@"removeContact"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(removeContactRsp:contactId:errorState:)])
        {
            [xmppContactDelegate removeContactRsp:Contact_Failure contactId:nil errorState:Contact_Timerout_Error];
        }
        return;
    }
    if ([reqType isEqualToString:@"remarkContact"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(remarkContactRsp:contactId:errorState:)])
        {
            [xmppContactDelegate remarkContactRsp:Contact_Failure contactId:nil errorState:Contact_Timerout_Error];
        }
        return;
    }
    if ([reqType isEqualToString:@"acceptContactInvite"])
    {
        if (xmppContactDelegate && [xmppContactDelegate respondsToSelector:@selector(acceptContactInviteRsp:contactId:errorState:)])
        {
            [xmppContactDelegate acceptContactInviteRsp:Contact_Failure contactId:nil errorState:Contact_Timerout_Error];
        }
        return;
    }
    //群组
    if ([reqType isEqualToString:@"initAllContactGroups"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(creatGroupNameRspState:groupId:withMsg:)])
        {
            [xmppGroupDelegate creatGroupNameRspState:Group_Failure groupId:msgId withMsg:@"超时"];
        }
        if (self.contactGroupCb) //针对获取所有群组及成员列表回调处理
        {
            self.contactGroupCb(NO);
        }
        return;
    }
    if ([reqType isEqualToString:@"creatGroupName"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(creatGroupNameRspState:groupId:withMsg:)])
        {
            [ChatGroupMgr deleteGroupListByGroupId:msgId];
            [xmppGroupDelegate creatGroupNameRspState:Group_Failure groupId:msgId withMsg:@"超时"];
        }
        return;
    }
    if ([reqType isEqualToString:@"updateGroupId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(updateGroupIdRspState:chatGroup:error:)])
        {
            [xmppGroupDelegate updateGroupIdRspState:Group_Failure chatGroup:msgId error:@"超时"];
        }
        return;
    }
    if ([reqType isEqualToString:@"deleteGroupId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(deleteGroupIdRspState:groupId:)])
        {
            [xmppGroupDelegate deleteGroupIdRspState:Group_Failure groupId:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"inviteGroupMember"] || [reqType isEqualToString:@"inviteGroupMemberArry"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(inviteGroupMemberRspState:groupId:error:)])
        {
            [xmppGroupDelegate inviteGroupMemberRspState:Group_Failure groupId:nil error:@"超时"];
        }
        return;
    }
    if ([reqType isEqualToString:@"kickoffGroupMember"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(kickoffGroupMemberRspState:groupId:errorMsg:)])
        {
            [xmppGroupDelegate kickoffGroupMemberRspState:Group_Failure groupId:nil errorMsg:@"超时"];
        }
        return;
    }
    if ([reqType isEqualToString:@"requestJoinGroupId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(requestJoinGroupIdRspState:groupId:errorMsg:)])
        {
            [xmppGroupDelegate requestJoinGroupIdRspState:Group_Failure groupId:nil errorMsg:@"超时"];
        }
        return;
    }
    if ([reqType isEqualToString:@"setGroupNickname"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(setGroupNicknameRspState:inGroupId:)])
        {
            [xmppGroupDelegate setGroupNicknameRspState:Group_Failure inGroupId:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"quitGroupId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(quitGroupIdRspState:groupId:)])
        {
            [xmppGroupDelegate quitGroupIdRspState:Group_Failure groupId:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"acceptGroupMemberId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(acceptGroupMemberIdRspState:memberId:joinGroupId:)])
        {
            [xmppGroupDelegate acceptGroupMemberIdRspState:Group_Failure memberId:nil joinGroupId:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"rejectGroupMemberId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(rejectGroupMemberIdRspState:memberId:joinGroupId:)])
        {
            [xmppGroupDelegate rejectGroupMemberIdRspState:Group_Failure memberId:nil joinGroupId:nil];
        }
        return;
    }
    if ([reqType isEqualToString:@"abdicateAdmininstrationGroupId"])
    {
        if (xmppGroupDelegate && [xmppGroupDelegate respondsToSelector:@selector(abdicateAdmininstrationGroupIdRspState:groupId:)])
        {
            [xmppGroupDelegate abdicateAdmininstrationGroupIdRspState:Group_Failure groupId:nil];
        }
        return;
    }
    
    [reqTimer invalidate];
    reqTimer = nil;
    [self.timerIdList removeObject:dic];
}

#pragma mark-------XMPPAutoPingDelegate------
//初始化并启动ping
- (void)autoPingProxyServer:(NSString*)strProxyServer

{
    //NSLog(@"ping.................................");
    self.xmppAutoPing = [[XMPPAutoPing alloc] init];
    
    
    [xmppAutoPing addDelegate:self delegateQueue: dispatch_get_main_queue()];
    [xmppAutoPing activate:xmppStream];

    xmppAutoPing.respondsToQueries = YES;
    
    //pingInterval 默认每（pingInterval／4）启动一次
    xmppAutoPing.pingInterval = 10 * 60;//ping 间隔时间
    xmppAutoPing.pingTimeout = 30;
    
    if (nil != strProxyServer)
    {
        xmppAutoPing.targetJID = [XMPPJID jidWithString: strProxyServer];//strProxyServer设置ping目标服务器，如果为nil,则监听socketstream当前连接上的那个服务器
    }
}

//卸载监听
- (void)deactivateXmppAutoPing
{
    [_xmppAutoPing   deactivate];

    [_xmppAutoPing   removeDelegate:self];
    
    self.xmppAutoPing = nil;
}

//ping XMPPAutoPingDelegate的委托方法:
- (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender
{
    WXLog(@"- (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender");
}

- (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender
{
    WXLog(@"- (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender");
    //ping 成功，返回pong
}

- (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender
{
    WXLog(@"- (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender");
    //ping 超时 ，卸载ping
 //   [self deactivateXmppAutoPing];
    //ping  超时，重新连接server
    [self becomeActive:nil];

    
}

#pragma mark----消息通知----
-(void)sendlocalNotification
{
    // 创建一个本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    //设置10秒之后
    NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
    if (notification != nil) {
        // 设置推送时间
        notification.fireDate = pushDate;
        // 设置时区
        notification.timeZone = [NSTimeZone defaultTimeZone];
        // 设置重复间隔
        notification.repeatInterval = kCFCalendarUnitDay;
        // 推送声音
        notification.soundName = UILocalNotificationDefaultSoundName;
        // 推送内容
        notification.alertBody = @"推送内容";
        //显示在icon上的红色圈中的数子
        notification.applicationIconBadgeNumber = 1;
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *info = [NSDictionary dictionaryWithObject:@"name"forKey:@"key"];
        notification.userInfo = info;
        //添加推送到UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:notification]; 
        
    }
}
#pragma mark----上传设备Token----
- (BOOL)ucfgroup_uploadDeviceToken:(NSString *)deviceToken owner:(NSString *)owner
{
    if (deviceToken == nil || owner == nil) {
        return NO;
    }
    
    NSString *uploadTokeniqID =[NSString stringWithFormat:@"uploadToken.%d",[self getRandomNumber:1000000 to:9000000]];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"id" stringValue:uploadTokeniqID];
    [iq addAttributeWithName:@"to" stringValue:kXMPPmyHostAddr];
    [iq addAttributeWithName:@"type" stringValue:@"set"];

    NSXMLElement *create = [NSXMLElement elementWithName:@"set"];
    [create addAttributeWithName:@"device" stringValue:@"ios"];
    [create addAttributeWithName:@"token" stringValue:deviceToken];
    
    NSXMLElement *tokenXmln = [NSXMLElement elementWithName:@"token" xmlns:@"urn:xmpp:token"];
    [tokenXmln addChild:create];
    
    [iq addChild:tokenXmln];
    
    [xmppStream sendElement:iq];

    return YES;
}
#pragma mark--设置消息免打扰----
- (BOOL)ucfgroup_SetMessageTrouble:(BOOL)isTuouble connectid:(NSString *)connectid
{
    NSString *tempstr = nil;
    NSString *tempconnectid;
    if ([connectid isEqualToString:@"all"]) {
        tempconnectid = @"all";
    }else{
        tempconnectid = [self convertToJid:connectid];
    }
    if (isTuouble) {
        tempstr = @"set";
    }else{
        tempstr = @"cancel";
    }
    NSString *uploadTokeniqID =[NSString stringWithFormat:@"messageTrouble.%d",[self getRandomNumber:1000000 to:9000000]];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"id" stringValue:uploadTokeniqID];
    [iq addAttributeWithName:@"to" stringValue:kXMPPmyHostAddr];
    [iq addAttributeWithName:@"type" stringValue:@"set"];
    
    NSXMLElement *create = [NSXMLElement elementWithName:@"set"];
    [create addAttributeWithName:@"action" stringValue:tempstr];
    [create addAttributeWithName:@"peer" stringValue:tempconnectid];
    
    NSXMLElement *stickyXmln = [NSXMLElement elementWithName:@"dnd" xmlns:@"urn:xmpp:dnd"];
    [stickyXmln addChild:create];
    
    [iq addChild:stickyXmln];
    
    [xmppStream sendElement:iq];
    
    return YES;
}
- (BOOL)ucfgroup_GetMessageTroubleConnectid:(NSString *)connectid{
    NSString *tempconnectid;
    if ([connectid isEqualToString:@"all"]) {
        tempconnectid = @"all";
    }else{
        tempconnectid = [self convertToJid:connectid];
    }
    NSString *uploadTokeniqID =[NSString stringWithFormat:@"messageTroubleget.%d",[self getRandomNumber:1000000 to:9000000]];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"id" stringValue:uploadTokeniqID];
    [iq addAttributeWithName:@"to" stringValue:kXMPPmyHostAddr];
    [iq addAttributeWithName:@"type" stringValue:@"get"];
    
    NSXMLElement *create = [NSXMLElement elementWithName:@"peer"];
    [create addAttributeWithName:@"jid" stringValue:tempconnectid];
    
    NSXMLElement *stickyXmln = [NSXMLElement elementWithName:@"dnd" xmlns:@"urn:xmpp:dnd"];
    [stickyXmln addChild:create];
    
    [iq addChild:stickyXmln];
    
    [xmppStream sendElement:iq];
    
    return YES;

}
#pragma mark -------------删除聊天服务器聊天记录---------
- (BOOL)ucfgroup_DeleteMessageWithConnectid:(NSString *)connectid{
    
    NSString * tempconnectid = [self convertToJid:connectid];
    NSString *deleteiqID =[NSString stringWithFormat:@"deletemessage.%d",[self getRandomNumber:1000000 to:9000000]];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"id" stringValue:deleteiqID];
    [iq addAttributeWithName:@"to" stringValue:kXMPPmyHostAddr];
    [iq addAttributeWithName:@"type" stringValue:@"set"];
    
    NSXMLElement *create = [NSXMLElement elementWithName:@"set"];
    [create addAttributeWithName:@"peer" stringValue:tempconnectid];
    [create addAttributeWithName:@"action" stringValue:@"delete"];
    
    NSXMLElement *stickyXmln = [NSXMLElement elementWithName:@"chat-history" xmlns:@"urn:xmpp:chat-history"];
    [stickyXmln addChild:create];
    
    [iq addChild:stickyXmln];
    
    [xmppStream sendElement:iq];
    
    return YES;
}
//检查文件绝对路径
- (NSString *)checkFileFullPathByFileName:(NSString *)filename
{
    NSString *loginName = [self truncateNSString:self.logRegWxUserObject.UserId To:kXMPPmyDomain];
    NSString *filePath2 = [DATABASE_PATH stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%@/image",loginName],filename]];
    return filePath2;
}


//检查测试服务器Or正式服务器
- (NSString *)getFileServer
{
    return kDefaultOpenApiUrl;

    //设置服务器

}

//***************************************独立使用接口--End*********************************
#pragma mark - -------****************------通用小方法--------***************-------
- (NSString *)generateXMPPresource
{
#warning message -去掉随机数！！！！[self getRandomNumber:000000 to:999999999]
    NSString *genXMPPres = [NSString stringWithFormat:@"%@",kXMPPmyResource];
    return genXMPPres;
}

//获取一个随机整数，范围在[from,to），包括from，不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1))); //+1,result is [from to]; else is [from, to)!!!!!!!
}

- (NSString *)getCurrentTime
{
    NSDate *nowUTC = [NSDate date];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    
    return [dateFormatter stringFromDate:nowUTC];
}
- (NSString *)convertToJid:(NSString *)jidName
{
    NSString *jidNameValid = nil;
    if (jidName != nil)
    {
        jidNameValid = [NSString stringWithString:jidName];
        NSRange range = [jidNameValid rangeOfString:kXMPPmyDomain];
        if (range.length >0)//包含
        {
        }
        else //不包含
        {
            jidNameValid = [NSString stringWithFormat:@"%@%@",jidName,kXMPPmyDomain];
        }
    }
    else
    {
    }
    WXLog(@"convertToJid: jidNameValid= %@",jidNameValid);
    return jidNameValid;
}

- (BOOL)findSubstring:(NSString *)substr inString:(NSString *)dststr
{
    if (dststr == nil || substr == nil) {
        return FALSE;
    }
    
    NSRange range = [dststr rangeOfString:substr];
    
    if (range.length >0)//包含
    {
        return TRUE;
    }
    else//不包含
    {
        return FALSE;
    }
}


//将某一字符从开始位置截取到指定字符处
- (NSString *)truncateNSString:(NSString *)srcStr To:(NSString *)toStr
{
    if (srcStr == nil) {
        return nil;
    }
    NSRange range = [srcStr rangeOfString:toStr];
    if (range.length == 0) {
        return srcStr;
    }
    NSString *str = [srcStr substringToIndex:range.location];
    return str;
}

- (BOOL)getPhoneContacts:(NSMutableArray*)contactMutableArray
{
    if (contactMutableArray == nil) {
        return NO;
    }
    
    CFErrorRef *error = nil;
    
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    
    __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        
    }
    else { // we're on iOS 5 or older
        accessGranted = YES;
    }
    
    //ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSMutableArray * contacts = contactMutableArray; //[[NSMutableArray alloc] init];
    
    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //姓
            //            NSString *firstName = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
            NSString *lastname = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
            
            //获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            
            NSMutableDictionary *addressBookDic = [[NSMutableDictionary alloc] init];
            [addressBookDic setValue:lastname forKey:@"Name"];
            [addressBookDic setValue:personPhone forKey:@"TelNumber"];
            [contacts addObject:addressBookDic];
        }
    }
    return YES;
}




@end
